﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using BrightIdeasSoftware;
using DevComponents.DotNetBar.Controls;
using PropertyGridEx;
using Toolkit.Library;
using TvdbLib;
using TvdbLib.Cache;
using TvdbLib.Data;
using TvdbLib.Data.Banner;
using WDTVHubGen.Base;
using WDTVHubGen.LoggingService;
using System.Web;
using WDTVHubGen.Util;
using WatTmdb.V3;

namespace WDTVHubGen
{
    /// <summary>
    /// Main form for the application
    /// I use the libraries for TheMovieDBLib which I have modified to work with languages, http://themoviedbapi.codeplex.com/ for full license and details. 
    /// Also had to modify to work with v2.1 of the api which changed some minor things 
    /// I also use the tvdblib api class for thetvdb.com http://code.google.com/p/tvdblib/ for full details and license
    /// FInally using the ObjectListView for the cool interface objects...  * ObjectListView - A listview to show various aspects of a collection of objects
    /// Author: Phillip Piper, full website: http://objectlistview.sourceforge.net/cs/index.html for full details and license
    /// Finally i have had a lot of help in debugging the members of the community.wdc.com forum! thanks guys
    /// </summary>
    public partial class frmMainForm : Form
    {
        private readonly List<VideoItem> movieList = new List<VideoItem>();
        private readonly List<VideoItem> tvList = new List<VideoItem>();
        private List<string> directoriesList = new List<string>();
        private List<int> colwidths = new List<int>(); 

        private ICacheProvider mCacheProvider;

        private Options options = new Options();
        private bool userImage = false;

        private bool aggressive;
        private bool InAutomationLoop = false;
        private bool StartingUp = true;

        private TvdbHandler m_tvdbHandler;
        private TmdbMovie movie;

        private int movieNumToShow;
        private int moviesFound;
        private TvdbSeries series = new TvdbSeries();
        private int seriesFound;
        private int seriesNumToShow;
        private List<string> validExtensions = new List<string>();
        private Dictionary<string, int> savedSeries = new Dictionary<string, int>();

        private string[] validsubs = new string[] { ".srt", ".sub", ".idx", ".ssa", ".smi", ".ass" };

        WatTmdb.V3.Tmdb api = null;

        #region Movie Controls ----------------------------------------------------------------------------------------------
        /// <summary>
        /// Removes the episode information from a tv show title using matching regexs
        /// </summary>
        /// <param name="cleanfilename">the "clean" filename to be modified</param>
        /// <returns>the filename without episode information</returns>
        private string RemoveEpisodeInformation(string cleanfilename)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In RemoveEpisodeInformation");

            // searches for S01E01 or 01x02 
            var rx = new Regex(@"(S(?<season>\d{1,2})E(?<episode>\d{2}))|((?<season>\d{1,2})x(?<episode>\d{1,2}))",
                               RegexOptions.IgnoreCase);

            MatchCollection matches = rx.Matches(cleanfilename);
            if (matches.Count > 0)
            {
                cleanfilename = cleanfilename.Substring(0, matches[0].Index);

                return cleanfilename;
            }

            // searches for combined episode and season 0203
            var rx2 = new Regex(@"(?<combined>\d{3,4})", RegexOptions.IgnoreCase);
            MatchCollection matches2 = rx2.Matches(cleanfilename);
            if (matches2.Count > 0)
            {
                cleanfilename = cleanfilename.Substring(0, matches2[0].Index);
                return cleanfilename;
            }

            //searches for one and two digits episode season  1x1
            var rx3 = new Regex(@"(?<season>\d{1,2})x(?<episode>\d{1,2})", RegexOptions.IgnoreCase);
            MatchCollection matches3 = rx3.Matches(cleanfilename);
            if (matches3.Count > 0)
            {
                cleanfilename = cleanfilename.Substring(0, matches3[0].Index);
                return cleanfilename;
            }

            // Searches for the word Season and Episode
            var rx4 = new Regex(@"season\s{0,1}(?<season>\d{1,2})\s{0,2}episode\s{0,1}(?<episode>\d{1,2})", RegexOptions.IgnoreCase);
            MatchCollection matches4 = rx4.Matches(cleanfilename);
            if (matches4.Count>0)
            {
                cleanfilename = cleanfilename.Substring(0, matches4[0].Index);
                return cleanfilename;
            }

            return cleanfilename;
        }

        private Match GetSEString(string filename)
        {
            //string gestring = "";
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In GetSEString");

            var rx = new Regex(@"(S(?<season>\d{1,2})E(?<episode>\d{2,3}))|(\[(?<season>\d{1,2})x(?<episode>\d{1,3})\])",
                               RegexOptions.IgnoreCase);
            MatchCollection matches = rx.Matches(filename);

            if (matches.Count > 0)
            {
                //gestring = matches[0].Groups["season"] + ":" + matches[0].Groups["episode"];
                return matches[0];
            }

            var rx3 = new Regex(@"(?<season>\d{1,2})x(?<episode>\d{2,3})", RegexOptions.IgnoreCase);
            MatchCollection matches3 = rx3.Matches(filename);
            if (matches3.Count > 0)
            {
                return matches3[0];
            } 
            
            
            // Searches for the word Season and Episode
            var rx4 = new Regex(@"season\s{0,1}(?<season>\d{1,2})\s{0,2}episode\s{0,1}(?<episode>\d{2,3})", RegexOptions.IgnoreCase);
            MatchCollection matches4 = rx4.Matches(filename);
            if (matches4.Count > 0)
            {
                return matches4[0];
            }

            // ty a different regex
         /* removed because it captures 300 the movie... lets hope this doesn't blow something else up
          * 
          * var rx2 = new Regex(@"(?<combined>\d{3,4})", RegexOptions.IgnoreCase);
            MatchCollection matches2 = rx2.Matches(filename);
            if (matches2.Count > 0)
                return matches2[0];
            */
            
            return null;
        }

        private void LoadVideoList(string path)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadVideoList");
            // clear the existing movielist first.
            movieList.Clear();
            olvcXMLExists.GroupKeyToTitleConverter = delegate(object key)
            {
                if (key.ToString() == "True")
                    return ("Processing Complete");
                return ("Not Processed");
            };

            olvcThumbPresent.GroupKeyToTitleConverter = delegate(object key)
            {
                if (key.ToString() == "True")
                    return ("Processing Complete");
                return ("Not Processed");
            };
            objectListViewMovie.PrimarySortColumn = olvcXMLExists;
            //string[] filelist = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);
          ////  objectListViewMovie.UseTranslucentHotItem = options.ShowCards;

            // Make the hot item show an overlay when it changes
          ////  objectListViewMovie.HotItemStyle.Overlay = new MovieCardOverlay();
          ////  objectListViewMovie.HotItemStyle = objectListViewMovie.HotItemStyle;

            Cursor = Cursors.WaitCursor;
            sbStatus.Text = string.Format("Loading Videos from Directory {1}{0}", path,
                                          (options.RecursiveSearch) ? "(and subfolders) " : string.Empty);

            Application.DoEvents();  // Allow this to be displayed...
            string[] filelist = null;
            try
            {
                filelist = Directory.GetFiles(path, "*.*", (options.RecursiveSearch) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
            }
            catch (Exception ex)
            {
                ExceptionHandler(ex, "Load Video List");
            }

            validExtensions = Util.Utilities.GetValidExtensions(options.ValidExtensions);

            if (filelist != null)
            {
                int fileTotal = filelist.Length;
                int fileCount = 0;
                int foundcount = 0;
                int foundnewcount = 0;
                int ignorecount = 0;

                sbProgress.Maximum = fileTotal + 1;
                sbProgress.Value = 0;

                foreach (string filename in filelist)
                {
                    sbStatus.Text = string.Format("Processing {0} of {1} Files", fileCount++, fileTotal);
                    sbProgress.Value = fileCount;
                    Application.DoEvents();
                    if (validExtensions.Contains(Path.GetExtension(filename).ToLower()))
                    {
                        foundcount++;
                        // i have a movie file... now I need to see if that movie file has an xml associated with it.
                        bool XMLProcessed = File.Exists(Path.ChangeExtension(filename, "xml"));
                        bool JPGProcessed = File.Exists(UpdateImageLocation(Path.ChangeExtension(filename, "jpg")));
                        bool SubsPresent = SubPresent(filename);
                        string seasonEpisode = string.Empty;
                        if (options.SuppressVOBProcessing)
                        {
                            if (Path.GetExtension(filename.ToLower()) != ".vob")
                                seasonEpisode =
                                    GetEpisodeSeason(CleanFileName(GetFileNameWithoutExtensionFast(filename)));
                            else if (Path.GetFileName(filename).ToUpper() == "VTS_01_0.VOB")
                            {
                                DirectoryInfo di = Directory.GetParent(filename);
                                string dirfilename = Path.GetFileName(di.FullName);
                                seasonEpisode =
                                    GetEpisodeSeason(CleanFileName(dirfilename));
                            }
                        } else seasonEpisode = GetEpisodeSeason(CleanFileName(GetFileNameWithoutExtensionFast(filename)));

                        //bool skipprocessing = (seasonEpisode != string.Empty) && (options.IgnoreTVOnMovies);

                        VideoItem videoItem = null;
                        if (XMLProcessed)
                        {

                            string fullpath = Path.GetDirectoryName(filename);
                            string strippedfilename = Path.GetFileNameWithoutExtension(filename);
                            string imagelocation = JPGProcessed ? UpdateImageLocation( Path.ChangeExtension(filename, "jpg")) : "notfound.jpg";
                            string newxmlfilename = fullpath + Path.DirectorySeparatorChar + strippedfilename + ".xml";
                            details movieDetails = DeserializeDetails(newxmlfilename);
                            if (movieDetails != null)
                            {

                                if (seasonEpisode != string.Empty)
                                {
                                    // this is a tv item... lets make it so...
                                    // check to see if hidden jpg names are used, if they are... deal.
                                    

                                    videoItem = new VideoItem(movieDetails.title, movieDetails.overview, filename,
                                                              Convert.ToInt32(seasonEpisode.Split(':')[0]),
                                                              Convert.ToInt32(seasonEpisode.Split(':')[1]),
                                                              imagelocation, true, true, SubsPresent, movieDetails.title,
                                                              movieDetails);

                                }
                                else videoItem = new VideoItem(movieDetails.title, movieDetails.overview, filename,
                                                               imagelocation, true, true, SubsPresent, movieDetails.title,
                                                               movieDetails);

                                movieList.Add(videoItem);
                            }
                            else
                            {
                                string cleanfilename = CleanFileName(GetFileNameWithoutExtensionFast(filename));
                                videoItem = new VideoItem(cleanfilename, filename, false, false, SubsPresent);
                                movieList.Add(videoItem);
                            }
                        }
                        else // no movie xml file found, so I need to parse the name and load it in the movielist anyway
                        {
                            if (seasonEpisode != string.Empty)
                            {

                                string cleanfilename = CleanFileName(GetFileNameWithoutExtensionFast(filename));
                                cleanfilename = RemoveEpisodeInformation(cleanfilename).Trim();

                                // deal with tv shows that rely on the directory to have name of show
                                if (cleanfilename.Trim() == string.Empty)
                                {
                                    cleanfilename = Directory.GetParent(filename).Name;
                                    if (cleanfilename.ToLower().StartsWith("season"))
                                    {
                                        cleanfilename = Directory.GetParent(filename).FullName;
                                        cleanfilename = Directory.GetParent(cleanfilename).Name;
                                    }

                                }

                                // cleanfilename = cleanfilename.Replace(seasonEpisode)
                                videoItem = new VideoItem(cleanfilename, filename,
                                                          Convert.ToInt32(seasonEpisode.Split(':')[0]),
                                                          Convert.ToInt32(seasonEpisode.Split(':')[1]), false, false,
                                                          SubsPresent);
                                if (options.SuppressVOBProcessing)
                                {
                                    if (Path.GetExtension(filename.ToLower()) != ".vob")
                                        movieList.Add(videoItem);
                                    else if (videoItem.VOBDirectory) movieList.Add(videoItem); else ignorecount++;
                                } else movieList.Add(videoItem);
                                foundnewcount++;
                            }
                            else
                            {

                                string cleanfilename = CleanFileName(GetFileNameWithoutExtensionFast(filename));
                                videoItem = new VideoItem(cleanfilename, filename, false, false, SubsPresent);
                                if (options.SuppressVOBProcessing)
                                {
                                    if (Path.GetExtension(filename.ToLower()) != ".vob")
                                        movieList.Add(videoItem);
                                    else if (videoItem.VOBDirectory) movieList.Add(videoItem); else ignorecount++;
                                }
                                else movieList.Add(videoItem);
                                foundnewcount++;


                            }

                        }

                        //else ignorecount++;
                    }
                }
                // finished....
                Cursor = Cursors.Default;
                sbProgress.Value = 0;
                sbStatus.Text =
                    string.Format(
                        "Done! Processed {0} Movies, Displaying {2}, {3} are Unprocessed, Ignored {4}. Subfolders {1}searched",
                        foundcount,
                        (options.RecursiveSearch) ? string.Empty : "not ", foundcount - ignorecount, foundnewcount,
                        ignorecount);
            }
        }

        /*
         * private void LoadMovieList(string path)
           {
               if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadMovieList");
               // clear the existing movielist first.
               movieList.Clear();
               olvcXMLExists.GroupKeyToTitleConverter = delegate(object key)
                                                            {
                                                                if (key.ToString() == "True")
                                                                    return ("Processing Complete");
                                                                return ("Not Processed");
                                                            };

               olvcThumbPresent.GroupKeyToTitleConverter = delegate(object key)
                                                               {
                                                                   if (key.ToString() == "True")
                                                                       return ("Processing Complete");
                                                                   return ("Not Processed");
                                                               };
               objectListViewMovie.PrimarySortColumn = olvcXMLExists;
               //string[] filelist = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);
               objectListViewMovie.UseTranslucentHotItem = options.ShowCards;

               // Make the hot item show an overlay when it changes
               objectListViewMovie.HotItemStyle.Overlay = new MovieCardOverlay();
               objectListViewMovie.HotItemStyle = objectListViewMovie.HotItemStyle;
            
               Cursor = Cursors.WaitCursor;
               sbStatus.Text = string.Format("Loading Movies from Directory {1}{0}", path,
                                             (options.RecursiveSearch) ? "(and subfolders) " : string.Empty);

               Application.DoEvents();  // Allow this to be displayed...
               string[] filelist = null;
               try
               {
                   filelist = Directory.GetFiles(path, "*.*", (options.RecursiveSearch) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
               }
               catch (Exception ex)
               {
                   ExceptionHandler(ex,"Load Movie List");
               }

               validExtensions = GetValidExtensions();

               int fileTotal = filelist.Length;
               int fileCount = 0;
               int foundcount = 0;
               int foundnewcount = 0;
               int ignorecount = 0;

               sbProgress.Maximum = fileTotal + 1;
               sbProgress.Value = 0;

               foreach (string filename in filelist)
               {
                   sbStatus.Text = string.Format("Processing {0} of {1} Files", fileCount++, fileTotal);
                   sbProgress.Value = fileCount;
                   Application.DoEvents();
                   if (validExtensions.Contains(Path.GetExtension(filename).ToLower()))
                   {
                       foundcount++;
                       // i have a movie file... now I need to see if that movie file has an xml associated with it.
                       bool XMLProcessed = File.Exists(Path.ChangeExtension(filename, "xml"));
                       bool JPGProcessed = File.Exists(Path.ChangeExtension(filename, "jpg"));
                       bool SubsPresent = SubPresent(filename);
                       string seasonEpisode = GetEpisodeSeason(CleanFileName(GetFileNameWithoutExtensionFast(filename)));
                       bool skipprocessing = (seasonEpisode != string.Empty) && (options.IgnoreTVOnMovies);

                       if (!skipprocessing)
                       {
                           if (XMLProcessed)
                           {
                               string fullpath = Path.GetDirectoryName(filename);
                               string strippedfilename = Path.GetFileNameWithoutExtension(filename);
                               string imagelocation = JPGProcessed ? Path.ChangeExtension(filename, "jpg") : "notfound.jpg";
                               string newxmlfilename = fullpath + Path.DirectorySeparatorChar + strippedfilename + ".xml";
                               details movieDetails = DeserializeDetails(newxmlfilename);
                               if (movieDetails != null)
                               {
                                   var VideoItem = new VideoItem(movieDetails.title, movieDetails.overview, filename,
                                                                 imagelocation, true, true, SubsPresent, movieDetails.title,
                                                                 movieDetails);
                                   using (Image image = Image.FromFile(Path.ChangeExtension(filename,"jpg")))
                                   {
                                       imageList1.Images.Add(image);
                                       imageList1.Images.SetKeyName(imageList1.Images.Count - 1, VideoItem.Title);
                                   }
                                   movieList.Add(VideoItem);
                               }
                               else
                               {
                                   string cleanfilename = CleanFileName(GetFileNameWithoutExtensionFast(filename));
                                   var VideoItem = new VideoItem(cleanfilename, filename, false, false,SubsPresent);
                                   movieList.Add(VideoItem);
                               }
                           }
                           else // no movie xml file found, so I need to parse the name and load it in the movielist anyway
                           {
                               string cleanfilename = CleanFileName(GetFileNameWithoutExtensionFast(filename));
                               var VideoItem = new VideoItem(cleanfilename, filename, false, false, SubsPresent);
                               if (options.SuppressVOBProcessing)
                               {
                                   if (Path.GetExtension(filename.ToLower()) != ".vob") 
                                        movieList.Add(VideoItem);
                                   else
                                       if (VideoItem.VOBDirectory) movieList.Add(VideoItem);
                               } else movieList.Add(VideoItem); 
                           foundnewcount++;
                           }
                       } else ignorecount++;
                   }
               }
               // finished....
               Cursor = Cursors.Default;
               sbProgress.Value = 0;
               sbStatus.Text =
                   string.Format(
                       "Done! Processed {0} Movies, Displaying {2}, {3} are Unprocessed, Ignored {4}. Subfolders {1}searched",
                       foundcount,
                       (options.RecursiveSearch) ? string.Empty : "not ", foundcount - ignorecount, foundnewcount,
                       ignorecount);

           }
           */
        private bool SubPresent(string filename)
        {
            // first pull out 3 parts of the filename. filename, sub language, and then sub extension
            string filefront = Path.GetFileNameWithoutExtension(filename);
            string[] files = Directory.GetFiles(Path.GetDirectoryName(filename), filefront + ".*", SearchOption.TopDirectoryOnly);

            if (files.Length > 0)
            {
                return files.Any(file => validsubs.Any(validsub => Path.GetExtension(file).ToLower() == validsub));
            }

            return false;
        }

        private bool RenameSubFiles(string oldfilename, string newnamefront)
        {
            // first pull out 3 parts of the filename. filename, sub language, and then sub extension

            string filefront = Path.GetFileNameWithoutExtension(oldfilename);
            string[] files = Directory.GetFiles(Path.GetDirectoryName(oldfilename), filefront + ".*", SearchOption.TopDirectoryOnly);
            string savename;

            if (files.Length > 0)
            {
                // string[] returnfiles = new string[files.Length];
                // int count = 0;
                foreach (string file in files)
                {
                    foreach (string validsub in validsubs)
                    {
                        if (Path.GetExtension(file).ToLower() == validsub)
                        {
                            // ok. now rename the file...
                            if (filefront != null)
                            {
                                savename = file.Replace(filefront, newnamefront);
                                File.Move(file, savename);
                            }
                        }
                    }

                }
                return true;
            }

            return false;


        }


        private string GetFileNameWithoutExtensionFast(string value)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In GetFileNameWithoutExtensionFast");
            // Find last available character.
            // ... This is either last index or last index before last period.
            int lastIndex = value.Length - 1;
            for (int i = lastIndex; i >= 1; i--)
            {
                if (value[i] == '.')
                {
                    lastIndex = i - 1;
                    break;
                }
            }
            // Find first available character.
            // ... Is either first character or first character after closest /
            // ... or \ character after last index.
            int firstIndex = 0;
            for (int i = lastIndex - 1; i >= 0; i--)
            {
                switch (value[i])
                {
                    case '/':
                    case '\\':
                        {
                            firstIndex = i + 1;
                            goto End;
                        }
                }
            }
        End:
            // Return substring.
            return value.Substring(firstIndex, (lastIndex - firstIndex + 1));
        }


        private void btnGetFiles_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnGetFiles_Click");
            if (timer1.Enabled) timer1.Enabled = false;
            if (Directory.Exists(cboPath.Text))
            {
                LoadVideoList(cboPath.Text);

                objectListViewMovie.OwnerDraw = true;
                objectListViewMovie.SetObjects(movieList);

                foreach (OLVListItem item in objectListViewMovie.Items)
                {
                    item.ImageKey = ((VideoItem)item.RowObject).Title;
                }

                objectListViewMovie.Refresh();

                // clean out the preview pane...
                pictureBox1.Image = null;
                flowLayoutPanel1.Controls.Clear();
                btnSelectAlternateMovies.Enabled = false;
                btnSaveThisOne.Enabled = false;
                lblMovieTitle.Text = "";
            }
            else
            {
                cboPath.ForeColor = Color.Red;
                btnGetFiles.Enabled = false;
                sbStatus.Text = string.Format("Movie Directory: {0} does not exist, please choose a valid directory",
                                              cboPath.Text);
            }
        }

        private string CleanFileName(string FileNameWithoutExtension)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In CleanFileName");
            // clean up the string for searching....
            // replace . with spaces...
            string returnValue = FileNameWithoutExtension;
            IEnumerable<string> spacereplace = GetReplacements();
            IEnumerable<string> subs = GetSubstitutions();

            returnValue = spacereplace.Aggregate(returnValue, (current, s) => current.ToLower().Replace(s, " "));

            returnValue = subs.Aggregate(returnValue, (current, sub) => current.Replace(sub.Split('=')[0], sub.Split('=')[1]));
            // Fix the the s
            if (returnValue.Contains(", the"))
            {
                returnValue = "the " + returnValue.Replace(", the", string.Empty);
            }



            return returnValue;
        }


        private void frmMainForm_Load(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In frmMainForm_Load");

            /** adding click once support.
             * AutoUpdater.Start("https://dl.dropboxusercontent.com/s/7utsb3oyb5th988/AppCast.xml");
            // check for new version*/
            using (WebClient client = new WebClient())
            {
                string newversion = client.DownloadString(@"https://dl.dropboxusercontent.com/s/24urru4aex73aw8/version.txt");
                string currentversion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

                if (newversion != currentversion)
                {
                    //tell the user...
                    string message =
                        string.Format(
                            "A new version exists:{0}, your current version is:{1}, visit wdtvhubgen.codeplex.com to update",newversion,currentversion);
                    MessageBox.Show(message, "New Version Exists", MessageBoxButtons.OK);
                }
            } 

            // Fill the recently used list of movie directories...
            if (File.Exists(@"DirectoriesList.xml"))
            {
                Utilities.Deserialize(directoriesList, @"DirectoriesList.xml");

                foreach (string directory in directoriesList)
                {
                    cboPath.AutoCompleteCustomSource.Add(directory);
                    cboPath.Items.Add(directory);
                }
            }


            try
            {
                if (File.Exists(@"ColumnWidths.xml"))
                {
                    Utilities.Deserialize(colwidths, @"ColumnWidths.xml");
                    int i = 0;
                    foreach (int colwidth in colwidths)
                    {
                        objectListViewMovie.Columns[i].Width = colwidth;
                        i++;
                    }
                }
            } catch (Exception ex)
            {
                
            }

            

            if (Directory.Exists(options.MovieDirectory))
            {
                cboPath.ForeColor = SystemColors.WindowText;
                cboPath.Text = options.MovieDirectory;
                btnGetFiles.Enabled = true;
                btnToggleHidden.Enabled = true;
            }
            else
            {
                //cboPath.ForeColor = Color.Red;
                cboPath.Text = options.MovieDirectory;
                btnGetFiles.Enabled = false;
                btnToggleHidden.Enabled = false;
                sbStatus.Text = string.Format("Movie Directory: {0} does not exist, please choose a valid directory",
                                              cboPath.Text);
            } 
          /*  if (Directory.Exists(options.TVShowDirectory))
            {
                txtSeriesPath.ForeColor = SystemColors.WindowText;
                txtSeriesPath.Text = options.TVShowDirectory;
                btnGetShows.Enabled = true;

            }
            else
            {
                txtSeriesPath.ForeColor = Color.Red;
                txtSeriesPath.Text = options.TVShowDirectory;
                btnGetShows.Enabled = false;
                sbStatus.Text = string.Format("TV Show Directory: {0} does not exist, please choose a valid directory",
                                              txtSeriesPath.Text);
            } */
            // Initialize TVDB handler
            m_tvdbHandler = new TvdbHandler(m_cacheProvider, "BEBB657E228E2DD7");
            // Load Options
            LoadOptionsTab();
            // Salary indicator column
            olvsSeasons.AspectGetter = delegate(object row)
                                                {
                                                    if (((VideoItem)row).VideoType == VideoTypeEnum.MovieType)
                                                        return "N/A";
                                                    return ((VideoItem)row).Season;
                                                };

            olvcVideoType.AspectGetter = delegate(object row)
            {
                if (((VideoItem)row).VideoType == VideoTypeEnum.MovieType) return "film";
                if (((VideoItem)row).VideoType == VideoTypeEnum.TVType) return "tv";
                return "adult";
            };
            olvcVideoType.Renderer = new MappedImageRenderer(new Object[] { "film", Resource1.film_smaller, "tv", Resource1.tv_smaller, "Lots", Resource1.film });

            // Install a custom renderer that draws the Tile view in a special way
            objectListViewMovie.ItemRenderer = new MovieCardRenderer();

           StartingUp = false;

        }

        private CustomProperty AddNewItem(string PropertyName, object objectName, string paramname, bool ReadOnly, string SectionName, string Description, Object customchoices)
        {
            CustomProperty newitem = new CustomProperty(PropertyName, objectName, ReadOnly, SectionName, Description, true);
            newitem.Tag = paramname;

            if (customchoices != null)
                switch (customchoices.GetType().ToString())
                {
                    case "System.Int32[]":
                        newitem.Choices = new CustomChoices((int[])customchoices, false);
                        break;
                    case "double[]":
                        newitem.Choices = new CustomChoices((double[])customchoices, false);
                        break;
                    case "object[]":
                        newitem.Choices = new CustomChoices((object[])customchoices, false);
                        break;
                    case "System.String[]":
                        newitem.Choices = new CustomChoices((string[])customchoices, false);
                        break;
                    case "System.Collections.ArrayList":
                        newitem.Choices = new CustomChoices((System.Collections.ArrayList)customchoices, false);
                        break;
                    default:
                        break;
                }

            return newitem;
        }

        private void SetDocCommentHeight(int value)
        {

            int difference = value - propertiesGrid.DocComment.Height;
            if (propertiesGrid.DocComment.Top - difference > propertiesGrid.Top)
            {
                propertiesGrid.DocComment.Height = value;
                propertiesGrid.DocComment.Top -= difference;
                propertiesGrid.Height -= difference;
                propertiesGrid.Refresh();
            }
        }

        private void LoadOptionsTab()
        {

            propertiesGrid.ShowCustomProperties = true;
            propertiesGrid.Item.Clear();
            SetDocCommentHeight(500);

            // oDocComment.Location = New Size(0, MyBase.Size.Height - value)
            // propertiesGrid.

            // Aggressive number lookup
            propertiesGrid.Item.Add(AddNewItem("Aggressive Words Count", options.AggressiveWords, "AggressiveWords", false,
                                               "Lookup Parameters", "How many words on the front of the movie/show name should be used for lookup, the rest of the words after this number will be removed and not used in search",
                                               new int[] { 1, 2, 3, 4 }));
            propertiesGrid.Item.Add(AddNewItem("Automatic Aggressive Lookup", options.AutoAggressiveLookup,"AutoAggressiveLookup", false, "Lookup Parameters",
                                               "Automatically Lookup a movie/tv show with using the Aggressive Method",
                                               null));

            // Run Time Formatting

            propertiesGrid.Item.Add(AddNewItem("Runtime format", options.RunTimeFormat, "RunTimeFormat", false, "Formatting Options",
                                               "Determines how the movie/show runtime will be displayed.  Choose hours and minutes to see a display like '1 hour 37 minutes'.  Choose minutes for a display like '97 minutes'",
                                               new string[] { "hours and minutes", "minutes" }));

            propertiesGrid.Item.Add(AddNewItem("Language for Descriptions", options.LanguageToReturn, "LanguageToReturn", false, "Formatting Options",
                                               "Determines the language used when querying themoviedb.org and thetvdb (some languages are not supported on both.\n en-english, de=deutch, it=italiano, pt=portuguese, es=espanol, fr=francai, ru=russian, zh=chinese",
                                               new string[] { "en", "de", "it", "pt", "es", "fr", "ru", "zh", "nl" }));

            propertiesGrid.Item.Add(AddNewItem("Overlay Episode Numbers on Shows", options.NumberOnShow, "NumberOnShow", false, "Formatting Options",
                                   "Overlay the current episode number on the thumbnail for an episode",
                                   null));

            // Verbose error handling
            propertiesGrid.Item.Add(AddNewItem("Verbose Error Reporting and Logging", options.VerboseErrors, "VerboseErrors", false, "Logging and Errors",
                                    "Verbose Errors will make any error reporting much more detailed, will also create a detailed log. Settings are none: produces no log and small error output, errors:logs only errors, verbose: logs EVERYTHING (caution, only use if really necessary)",
                                    null));

            propertiesGrid.Item.Add(AddNewItem("Save .JPG with Metadata", options.SavePictureWithMetadata, "SavePictureWithMetadata", false, "Formatting Options",
                                    "Determines whether the jpg should be saved with the metadata, this allows you to have your own custom jpgs.", null));


            propertiesGrid.Item.Add(AddNewItem("Suppress VOB Processing", options.SuppressVOBProcessing, "SuppressVOBProcessing", false, "Lookup Parameters",
                                    "Suppresses VOB processing, except for VTS_01_0.VOB in a directory. Use this when you want to process directories full of VOBs with the directory correctly named to movie", null));

            propertiesGrid.Item.Add(AddNewItem("Save Backdrops in XML", options.SaveBackdrops, "SaveBackdrops", false, "Formatting Options",
                                               "Save teh Backdrops in the xml file, or allow them not to be saved", null));

            propertiesGrid.Item.Add(AddNewItem("Use Original Filenames", options.UseOriginalFilenames, "UseOriginalFilenames", false, "Formatting Options",
                                               "Dont rename files during processing, use the original filenames", null));

            // Remove Words.

            propertiesGrid.Item.Add(AddNewItem("Remove Words", options.RemoveWords.Split(','), "RemoveWords", false, "Formatting Options",
                                    "Words to Remove from the movie/show title before processing, these are normally downloaded add-ons and other useless sh*t", null));

            propertiesGrid.Item.Add(AddNewItem("Supported Movie Extensions", options.ValidExtensions.Split(','), "ValidExtensions", false, "Formatting Options",
                                   "Valid Movie Extensions to find when searching a directory", null));

            propertiesGrid.Item.Add(AddNewItem("Substitutions", options.Substitutions.Split(','), "Substitutions", false, "Formatting Options",
                                   "Words to Substitute one for the other. rare", null));

            propertiesGrid.Item.Add(AddNewItem("Special Characters", options.SpecialCharacters.Split(','), "SpecialCharacters", false, "Formatting Options",
                                   "Special Characters to Substitute one for the other in filenames and in titles, never used anywhere else", null));


            propertiesGrid.Item.Add(AddNewItem("Recursive File Lookup", options.RecursiveSearch, "RecursiveSearch", false, "Lookup Parameters",
                                    "Recursively search movie/show folders and subfolders from the top folder. WARNING: Turning this feature on will dramtically increase wait time after clicking 'Get Movies/Shows'",
                                    null));

            propertiesGrid.Item.Add(AddNewItem("Ignore TV on Movies", options.IgnoreTVOnMovies, "IgnoreTVOnMovies", false, "Lookup Parameters",
                                    "When a tv show is found in a movie directory during a get files, it will not be processed and not shown on list.",
                                    null));


            propertiesGrid.Item.Add(AddNewItem("DescriptionTemplate", options.DescriptionTemplate, "DescriptionTemplate", false,
                           "Templates", "Template for the Description\n[%Description%] - Description of the Videos  [%Rating%] star rating of show [%MPAA%] mpaa rating of show [%SeasonNumber%] - Number of the Season         [%EpisodeNumber%] - Number of the Episode\n[%SeasonNumberNoZero%] Season number without a leading zero (single numbers are single)\n[%EpisodeNumberNoZero%] Episode number without a leading zero (single numbers are single)\n[%EpisodeName%] - Name of the Episode [%Year%] - Year Movie was released", null));

           
            propertiesGrid.Item.Add(AddNewItem("TV Title Template", options.TVTitleTemplate, "TVTitleTemplate", false,
                           "Templates", "Template for the TV Show Title\n[%SeriesName%] - Name of the Series         [%SeasonNumber%] - Number of the Season         [%EpisodeNumber%] - Number of the Episode\n[%SeasonNumberNoZero%] Season number without a leading zero (single numbers are single)\n[%EpisodeNumberNoZero%] Episode number without a leading zero (single numbers are single)\n[%EpisodeName%] - Name of the Episode         [%Dots%] - Replaces all spaces with Dots (put this at the end)         [%UnderLines%] - Replaces all spaces with _ (use this last)         [%Year%] - Year Movie was released", null));

            propertiesGrid.Item.Add(AddNewItem("Movie Title Template", options.MovieTitleTemplate, "MovieTitleTemplate", false,
                                               "Templates", "Template for the Movie Title\n[%MovieName%] - Name of the Movie\n[%Year%] - Year Movie was released\n[%Dots%] - Replaces all spaces with Dots (put this at the end)\n[%UnderLines%] - Replaces all spaces with _ (use this last)", null));

            propertiesGrid.Item.Add(AddNewItem("TV File Template", options.TVFileTemplate, "TVFileTemplate", false,
                                               "Templates", "Template for the TV Show File on Disk\n[%SeriesName%] - Name of the Series\n[%SeasonNumber%] - Number of the Season\n[%EpisodeNumber%] - Number of the Episode\n[%SeasonNumberNoZero%] Season number without a leading zero (single numbers are single)\n[%EpisodeNumberNoZero%] Episode number without a leading zero (single numbers are single)\n[%EpisodeName%] - Name of the Episode\n[%Dots%] - Replaces all spaces with Dots (put this at the end)\n[%UnderLines%] - Replaces all spaces with _ (use this last)", null));

            propertiesGrid.Item.Add(AddNewItem("Movie File Template", options.MovieFileTemplate, "MovieFileTemplate", false,
                                               "Templates", "Template for the Movie File on Disk\n[%MovieName%] - Name of the Movie\n[%Year%] - Year Movie was released\n[%RunTime%] - Length of movie as hours and mins\n[%Dots%] - Replaces all spaces with Dots (put this at the end)\n[%UnderLines%] - Replaces all spaces with _ (use this last)", null));




            propertiesGrid.Item.Add(AddNewItem("Show Cards on Details", options.ShowCards, "ShowCards", false, "Formatting Options",
                                   "Shows the card view on the details screen, use this if you want the card when image is too small", null));


            propertiesGrid.Refresh();

            /* object myremoves = options.RemoveWords.Split(',');
             propertiesGrid.Item.Add("RemoveWords", ref myremoves, "RemoveWords", false, "Lookup Parametersroperty", "Represent the PropertyGridEx Item collection.",true);
             */
        }


        private void btnProcess_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnProcess_Click");
            Cursor = Cursors.WaitCursor;
            int noXMl = movieList.Count(item => !item.XmlPresent);
            // Count the number of unchecked items..
            sbProgress.Maximum = noXMl;
            sbProgress.Value = 0;

            int moviesUpdated = 0;
            InAutomationLoop = true;
            foreach (VideoItem item in movieList)
            {
                if (!item.XmlPresent)
                {
                    //OLVSelectedIndex = index;
                    ShowDetailsOnCurrentOLVItem(item); // OLVSelectedIndex);
                    Application.DoEvents();

                    if (SaveCurrentItem(item)) moviesUpdated++;
                    sbStatus.Text = string.Format("Processing {0} of {1} Videos ", moviesUpdated, noXMl);
                    sbProgress.Value++;
                    Application.DoEvents();
                }

            }
            InAutomationLoop = false;
            sbProgress.Value = 0;
            sbStatus.Text = string.Format("Done Processing {0} Movies, {1} Saved. {2} Errors", noXMl, moviesUpdated,
                                          noXMl - moviesUpdated);
            Cursor = Cursors.Default;
        }

        private details DeserializeDetails(string filename)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In DeserializeDetails");
            // Create an instance of the XmlSerializer specifying type and namespace.
            var serializer = new XmlSerializer(typeof(details));
            details theDetails = new details();
            FileStream fs = new FileStream(filename, FileMode.Open);
            try
            {
                // A FileStream is needed to read the XML document.

                XmlReader reader = XmlReader.Create(fs);

                // Declare an object variable of the type to be deserialized.

                // Use the Deserialize method to restore the object's state.
                theDetails = (details)serializer.Deserialize(reader);
            }
            catch (Exception ex)
            {
                // XmlException innerex = (XmlException) ex.InnerException;
                // long lnum = innerex.LineNumber;
                // ReplaceSpecialChars(lnum, filename);
                theDetails = null;
            }
            finally
            {
                fs.Close();
            }

            return theDetails;
        }

        private void LoadDetailPanelWithMovieDetails(details movieDetails, FlowLayoutPanel flpanel, ReflectionLabel reflectionlabel)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadDetailPanelWithMovieDetails");
            // Fill in the Flow layout with all of the movie details that are filled :)
            try
            {
                reflectionlabel.Visible = true;
                reflectionlabel.Text =
                    string.Format("<b><font size=\"+6\">Movie: <font color=\"#B02B2C\"> <i>{0}</i></font></font></b>",
                                  movieDetails.title);

                flpanel.Controls.Clear(); // remove the old ones...
                timer1.Enabled = true;
                timer1.Tag = movieDetails;
                //AddMovieDetailPictureBox(flpanel);
                AddMovieDetailHeader(flpanel, "Movie Details");
                AddMovieDetail(flpanel, "Movie Name:", movieDetails.title);
                AddMovieDetail(flpanel, "Release Date:", movieDetails.year);
                AddMovieDetail(flpanel, "MPAA Rating:", movieDetails.mpaa);
                /*runtime
                int runtimetotalmins = Convert.ToInt32(movie.runtime);
                int runtimehours = runtimetotalmins / 60;
                int runtimemins = runtimetotalmins - (60 * runtimehours);
                string mdruntime = options.RunTimeFormat == "hours and minutes" ? string.Format("{0}h {1}", runtimehours, runtimemins) : string.Format("{0}", runtimetotalmins);
               */
                string mdruntime = string.Format("{0} minutes", movieDetails.runtime);
                AddMovieDetail(flpanel, "Length:", mdruntime);
                AddMovieDetail(flpanel, "Rating:", movieDetails.rating);
                string genre = movieDetails.genre.Aggregate("", (current, cat) => current + (cat.Value + ","));
                AddMovieDetail(flpanel, "Genre:", genre.Trim(','));
                AddMovieDetailHeader(flpanel, "Cast and Crew");
                foreach (detailsActor castPerson in movieDetails.actor)
                {
                    AddMovieDetail(flpanel, castPerson.role + ":", castPerson.name);
                }
                AddMovieDetailHeader(flpanel, "Synopsis");
                AddMovieDetail(flpanel, "", movieDetails.overview);
            }
            catch (Exception ex)
            {
                // throw this away...
            }

        }

        private bool LoadVideoDetails(VideoItem item)
        {
            switch (item.VideoType)
            {
                case VideoTypeEnum.MovieType:
                    return LoadMovieDetails(item);
                    break;
                case VideoTypeEnum.TVType:
                    return LoadTVDetails(item);
                    break;
                case VideoTypeEnum.AdultType:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            return false;
        }

        private string GetMovieSearchResults()
        {

            var request =
                System.Net.WebRequest.Create("http://themoviedb.apiary.io/3/search/movie") as System.Net.HttpWebRequest;
            request.Method = "GET";
            request.Accept = "application/json";
            request.ContentLength = 0;
            string responseContent;
            using (var response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    responseContent = reader.ReadToEnd();
                }
            }
            return responseContent;
        }


        private bool LoadMovieDetails(VideoItem item) //int olvindex, string cleanfilename, string uncleanfilename)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadMovieDetails");
            // before running this... remove a cd1 or cd2 and update clean file name
            int cd1 = item.CleanFileName.IndexOf("cd1");
            int cd2 = item.CleanFileName.IndexOf("cd2");
            string tempCleanName = item.CleanFileName;
            if (cd1 != -1)
                tempCleanName = tempCleanName.Remove(cd1, 3);
            if (cd2 != -1)
                tempCleanName = tempCleanName.Remove(cd2, 3);

            if (aggressive) tempCleanName = AggressiveCleanName(tempCleanName);


            try
            {
                api = new Tmdb("f703f0d3679c29df8855db6c80f382c8");
                // var api = new TmdbAPI("f703f0d3679c29df8855db6c80f382c8");
                //TmdbMovie[] movies = api.MovieSearch(tempCleanName, options.LanguageToReturn); //, options.LanguageToReturn);
                                
                // try to detect a year in teh movie name... if there strip it out and everything after it.... and use the year in the search... wowo.

                string pattern = @"\d{4}";
                int yearsearch = -1;
                int yeartoSearch = 1970;
                Regex r = new Regex(pattern);
                MatchCollection matches = r.Matches(tempCleanName);
                if (matches.Count == 1) yearsearch = 0;
                if (matches.Count > 1) yearsearch = 1;
                TmdbMovieSearch movies;
                if (yearsearch!= -1)
                tempCleanName = r.Replace(tempCleanName, string.Empty,1,yearsearch);

                if (yearsearch == -1)
                    movies = api.SearchMovie(tempCleanName, 1, options.LanguageToReturn);
                else
                {
                    yeartoSearch = Convert.ToInt32(matches[yearsearch].Value);
                    tempCleanName = tempCleanName.Remove(matches[yearsearch].Index).Trim(' ');
                    movies = api.SearchMovie(tempCleanName, 1, options.LanguageToReturn, true, yeartoSearch);
                }
                
                //

                moviesFound = movies.results.Count;

                if (moviesFound > 1)
                {
                    btnSelectAlternateMovies.Text = string.Format("{1} of {0} Movies Found", moviesFound,
                                                                  movieNumToShow + 1);
                    btnSelectAlternateMovies.Tag = tempCleanName;
                    if (InAutomationLoop)
                    {

                        if (movies != null && movies.results.Count > 0)
                        {
                            MovieSearchResultForm form = new MovieSearchResultForm(movies.results,tempCleanName);
                            form.StartPosition = FormStartPosition.Manual;
                            form.Left = this.Left + this.Width / 2 - form.Width / 2;
                            form.Top = this.Top + this.Height / 2 - form.Height / 2;
                            DialogResult res = form.ShowDialog();
                            if (res == DialogResult.OK)
                            {
                                // Now do something with the series that I picked... using form.Selection.Id
                                LoadMovieByID(form.Selection.id, item, cd1, cd2);
                                return true;
                            }
                            return false;
                        }
                    }
                }
                else
                {
                    btnSelectAlternateMovies.Text = "Only 1 Movie Found";
                    btnSelectAlternateMovies.Enabled = false;

                }

                if (moviesFound > 0)
                {
                    LoadMovieByID(movies.results[movieNumToShow].id, item, cd1, cd2);
                    return true;
                }
                // else
            }
            catch (Exception ex)
            {
                ExceptionHandler(ex, "LoadMovieDetails");
            }
            return false;
        }

        private string AggressiveCleanName(string tempCleanName)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In AggressiveCleanName");
            // pull out first two words and discard the rest...
            string temp = "";

            int wordcount = options.AggressiveWords;

            string[] words = tempCleanName.Split(' ');
            if (words.Length > (wordcount - 1))
            {
                for (int i = 0; i < wordcount; i++)
                {
                    temp += words[i] + " ";
                }
                temp = temp.Trim();
            }

            return temp;
        }


        private void LoadNextPicture(PictureBox pb)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadNextPicture");
            int movieid = Convert.ToInt32(pb.Tag.ToString().Split('.')[0]);
            int picturecount = Convert.ToInt32(pb.Tag.ToString().Split('.')[1]);

            bool used = false;
            //TmdbAPI api = new TmdbAPI("f703f0d3679c29df8855db6c80f382c8");
            // use the new API to get images...
            //
            TmdbMovieImages images = api.GetMovieImages(movie.id);
            TmdbConfiguration config = api.GetConfiguration();
            Uri baseUri = new Uri(config.images.base_url);
               
            for (int i = picturecount; i < images.posters.Count; i++)
            {
                //if ((movie.Images[i].Type == TmdbImageType.poster) && (movie.Images[i].Size == "cover"))
                // TmdbImageSize.cover))
                {
                    Uri myUri = new Uri(baseUri, "w154" + images.posters[i].file_path);
                    LoadPictureBox(pictureBox1, myUri.AbsoluteUri);
                    pictureBox1.Tag = string.Format("{0}.{1}", movie.id, i + 1);
                    used = true;
                    break;
                }
            }
            if (!used)
            {
                pb.Tag = string.Format("{0}.0", movieid);
                LoadNextPicture(pb);
            }
        }

        private void LoadNextTVPicture(PictureBox pb)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadNextTVPicture");
            int seriesid = Convert.ToInt32(pb.Tag.ToString().Split('.')[0]);
            int picturecount = Convert.ToInt32(pb.Tag.ToString().Split('.')[1]);
            int season = Convert.ToInt32(pb.Tag.ToString().Split('.')[2]);
            int episode = Convert.ToInt32(pb.Tag.ToString().Split('.')[3]);
            bool used = false;

            TvdbLanguage lang = new TvdbLanguage(10, "German", options.LanguageToReturn);//TvdbLanguage.DefaultLanguage
            series = m_tvdbHandler.GetSeries(seriesid, lang, true, true, true, true);

            int tcount = 0;
            int thumbnailcount = series.SeasonBanners.Count(image => image.Season == Convert.ToInt32(season));
            var thumbs = new detailsThumbnail[thumbnailcount];
            foreach (TvdbSeasonBanner image in series.SeasonBanners)
            {
                if (image.Season == Convert.ToInt32(season))
                {
                    thumbs[tcount] = new detailsThumbnail
                                         {
                                             Value = TvdbLinkCreator.CreateBannerLink(image.BannerPath)
                                         };
                    tcount++;
                }
            }

            if (picturecount <= tcount)
            {
                LoadPictureBox(pictureBox1, thumbs[picturecount - 1].Value); // movie.Images[i].Url);
                pictureBox1.Tag = string.Format("{0}.{1}.{2}.{3}", seriesid, picturecount + 1, season, episode);
                used = true;
            }


            if (!used)
            {
                pb.Tag = string.Format("{0}.1.{1}.{2}", seriesid, season, episode);
                LoadNextTVPicture(pb);
            }
        }

        private void AddMovieDetail(FlowLayoutPanel flpanel, string caption, string text)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In AddMovieDetail");
            var lbl2 = new Label
                           {
                               Size = new Size(250, 13),
                               MaximumSize = new Size(250, 80),
                               AutoSize = true,
                               Dock = DockStyle.Left,
                               TabIndex = 1,
                               Text = text,
                               TextAlign = ContentAlignment.MiddleLeft,
                               Width = 100,
                               Margin = new Padding(0),
                               BackColor = System.Drawing.Color.Transparent
                           };

            var lbl1 = new Label
                           {
                               Size = new Size(150, 13),
                               Dock = DockStyle.Right,
                               TabIndex = 0,
                               Text = caption,
                               TextAlign = ContentAlignment.TopRight,
                               Width = 150,
                               Margin = new Padding(0),
                               BackColor = System.Drawing.Color.Transparent
                           };

            var tlpanel = new TableLayoutPanel
                              {
                                  RowCount = 1,
                                  Size = new Size(450, 13),
                                  AutoSize = true,
                                  AutoSizeMode = AutoSizeMode.GrowOnly,
                                  ColumnCount = 2,
                                  BackColor = System.Drawing.Color.Transparent
                              };
            tlpanel.ColumnStyles.Add(new ColumnStyle());
            tlpanel.ColumnStyles.Add(new ColumnStyle());
            tlpanel.Controls.Add(lbl1, 0, 0);
            tlpanel.Controls.Add(lbl2, 1, 0);

            tlpanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));


            if (caption == string.Empty) // full wrap both columns
            {
                lbl2.MaximumSize = new Size(350, 100);
                lbl2.Margin = new Padding(3);
                flpanel.Controls.Add(lbl2);
            }
            else flpanel.Controls.Add(tlpanel);
        }


        private void AddMovieDetailHeader(FlowLayoutPanel flpanel, string header)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In AddMovieDetailHeader");
            var lbl1 = new Label
                           {
                               Font = new Font("Microsoft Sans Serif", 9.75F, FontStyle.Bold, GraphicsUnit.Point, ((0))),
                               Text = header,
                               TextAlign = ContentAlignment.MiddleCenter,
                               AutoSize = true,
                               BackColor = System.Drawing.Color.Transparent
                           };

            flpanel.Controls.Add(lbl1);
        }

        private details LoadTheDetails(TmdbMovie movie, string moviefilename)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadTheDetails");
            var md = new details();
            int actorcount = 0;
            int catcount = 0;
            int currentactor = 0;
            int thumbnailcount = 0;
            int backdropcount = 0;

            try
            {
                // Count the number of 
               /* replace with new api calls  foreach (TmdbImage image in movie.Images)
                {
                    if ((image.Type == TmdbImageType.poster) && (image.Size == "thumb")) //TmdbImageSize.thumb))
                        thumbnailcount++;
                    if ((image.Type == TmdbImageType.backdrop) && (image.Size == "poster")) // TmdbImageSize.poster)) 
                        backdropcount++;
                }
                */

                TmdbMovieImages images = api.GetMovieImages(movie.id);
                TmdbConfiguration config = api.GetConfiguration();
                Uri baseUri = new Uri(config.images.base_url);
                var thumbs = new detailsThumbnail[images.posters.Count];
                var backs = new detailsBackdrop[images.backdrops.Count];

                int tcount = 0;
                int bdcount = 0;

               
                foreach (Poster poster in images.posters)
                { 
                    Uri myUri = new Uri(baseUri, "w154" + poster.file_path);
                    thumbs[tcount] = new detailsThumbnail
                        { Value = myUri.AbsoluteUri };
                    tcount++;
                }

                foreach (Backdrop backdrop in images.backdrops)
                {
                    Uri myUri = new Uri(baseUri,"w780"+backdrop.file_path);
                    backs[bdcount] = new detailsBackdrop() {Value = myUri.AbsoluteUri};
                    bdcount++;
                }

                /*foreach (var image in images)
                {
                    if ((image.Type == TmdbImageType.poster) && (image.Size == "thumb")) //TmdbImageSize.thumb))
                    {
                        thumbs[tcount] = new detailsThumbnail { Value = image.Url };
                        tcount++;
                    }
                    if ((image.Type == TmdbImageType.backdrop) && (image.Size == "poster")) //TmdbImageSize.poster))
                    {
                        backs[bdcount] = new detailsBackdrop { Value = image.Url };
                        bdcount++;
                    }
                }*/

                md.backdrop = options.SaveBackdrops ? backs : null;
                md.thumbnail = thumbs;

                TmdbMovieCast cast = api.GetMovieCast(movie.id); //MovieID)

                actorcount = cast.cast.Count;// movie.Cast.Count(castPerson => castPerson.Job == "Actor");
                var actors = new detailsActor[actorcount];
                foreach (Cast castPerson in cast.cast)
                {
                        var actor = new detailsActor { name = castPerson.name, role = castPerson.character };
                        actors[currentactor] = new detailsActor();
                        actors[currentactor] = actor;
                        currentactor++;
                }
                foreach (Crew crew in cast.crew)
                {
                    if (crew.job == "Director")
                        md.director = crew.name;
                }
                md.actor = actors;
                //md.IMDBLink = string.Format(@"http://www.imdb.com/title/{0}/", movie.ImdbId);
                
                var cats = new detailsGenre[movie.genres.Count()];
                foreach (MovieGenre category in movie.genres)
                {
                    var cat = new detailsGenre { Value = category.name };
                    cats[catcount] = new detailsGenre();
                    cats[catcount] = cat;
                    catcount++;
                }
                md.genre = cats;

                TmdbMovieReleases release = api.GetMovieReleases(movie.id);
                foreach (ReleaseCountry country in release.countries)
                {
                    md.mpaa = country.certification;

                }
                //old way 
                
                //md.mpaa = movie.Certification;
                
                md.prevgenre = "N/A";
                md.prevtitle = Path.GetFileName(moviefilename);
               
                md.rating = movie.vote_average.ToString();
                int runtimetotalmins = Convert.ToInt32(movie.runtime);
                int runtimehours = runtimetotalmins/60;
                int runtimemins = runtimetotalmins - (60*runtimehours);
                md.runtime = options.RunTimeFormat == "hours and minutes" ? string.Format("{0}h {1}", runtimehours, runtimemins) : string.Format("{0}", runtimetotalmins);
                /*runtime*/
               // md.runtime = movie.runtime.ToString();
                //md.studio = movie.tudios.Length > 0 ? movie.Studios[0].Name : string.Empty;

                md.title = movie.title.Replace(':', '-').Replace('\\', ' ').Replace('/', ' ');
                
                //md.trailer = movie.Trailer;
                TmdbMovieTrailers trailers = api.GetMovieTrailers(movie.id);
                if (trailers.youtube.Count>0) md.trailer = string.Format("http://www.youtube.com/v/{0}", trailers.youtube[0].source);
                md.url = new detailsUrl[1];
                var urls = new detailsUrl[1];
                urls[0] = new detailsUrl { cache = "tmdb-.xml", function = "GetTMDBThumbsById" };
                md.url = urls;
                //md.year = movie.ReleasedString;
                DateTime releaseDate = Convert.ToDateTime(movie.release_date);
                if (movie.release_date != null)
                {

                    md.year = string.Format("{0}-{1:00}-{2:00}", releaseDate.Year, releaseDate.Month,
                                            releaseDate.Day);
                    md.firstaired = md.year;
                }
                md.overview = GenerateDescriptionFromTemplate(movie);//JAG
                md.plot = movie.overview;  //JAG
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
            return md;
        }

        


        private void btnPathBrowse_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnPathBrowse_Click");
            folderBrowserDialog1.SelectedPath = cboPath.Text;
            if (folderBrowserDialog1.ShowDialog() != DialogResult.Cancel)
            {
                cboPath.Text = folderBrowserDialog1.SelectedPath;
                // before doing anything, add this to the saved list and persist
                if (!directoriesList.Contains(cboPath.Text))
                {
                    directoriesList.Add(cboPath.Text);
                    Utilities.SerializeObject(directoriesList,"DirectoriesList.xml");

                   cboPath.AutoCompleteCustomSource.Add(cboPath.Text);
                   cboPath.Items.Add(cboPath.Text);
                   
                    // set the path again after the list additions
                }
                options.MovieDirectory = cboPath.Text;
                options.SaveSettings();
                btnGetFiles.Enabled = true;
                btnToggleHidden.Enabled = true;
                cboPath.ForeColor = SystemColors.WindowText;
                sbStatus.Text = "";
            }
        }

        private void chkShowUnprocessed_CheckedChanged(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In chkShowUnprocessed_CheckedChanged");
            //PopulateList(txtPath.Text, chkShowUnprocessed.Checked, lvwFileList,showtype.movie);
            if (chkShowUnprocessed.Checked)
            {
                objectListViewMovie.ShowGroups = true;
                objectListViewMovie.PrimarySortColumn = olvcXMLExists;
            }
            else
            {
                objectListViewMovie.ShowGroups = false;
                objectListViewMovie.PrimarySortColumn = olvcTitle;
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnNext_Click");
            // Increment the movienumber to look up...
            if (moviesFound > (movieNumToShow + 1))
            {
                movieNumToShow++;
                var item = (VideoItem)objectListViewMovie.SelectedObject;
                ShowDetailsOnCurrentOLVItem(item);
            }
        }



        private string ChangeDirectoryName(string fullpath, string newfiletitle)
        {
            string olddirectoryname = Directory.GetParent(fullpath).FullName;
            string newdirectoryname = Directory.GetParent(olddirectoryname).FullName + Path.DirectorySeparatorChar + newfiletitle;
            Directory.Move(olddirectoryname, newdirectoryname);
            return newdirectoryname;
        }

        private string RemoveIllegalPathCharacters(string newfilename)
        {
            string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());

            foreach (char c in invalid)
            {
                newfilename = newfilename.Replace(c.ToString(), string.Empty);
            }
            return newfilename;
        }

        private bool SaveCurrentItem(VideoItem item) // int index)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In SaveCurrentItem");

            details md = item.MovieDetail;
            Cursor.Current = Cursors.WaitCursor;

            if (md != null)
            {
                // get the correct sized picture
                string thumbnailurl = pictureBox1.ImageLocation;

                try
                {
                    string newfiletitle = string.Empty;
                    string fullpath;
                    string newxmlfilename;
                    string newdirectoryname;

                    if (item.VideoType == VideoTypeEnum.MovieType)
                    {
                        if (item.VOBDirectory)
                        {
                            newfiletitle = (options.UseOriginalFilenames) ? Path.GetFileNameWithoutExtension(item.FullFileName) : ProcessTags(options.MovieFileTemplate, item.MovieDetail);
                            fullpath = Path.GetDirectoryName(item.FullFileName);
                            newdirectoryname = ChangeDirectoryName(item.FullFileName, newfiletitle);
                            newfiletitle = Path.GetFileNameWithoutExtension(item.FullFileName);
                            // dont rename the files, just the path...
                            newxmlfilename = newdirectoryname + Path.DirectorySeparatorChar + RemoveIllegalPathCharacters(newfiletitle) + ".xml";
                            fullpath = newdirectoryname;
                        }
                        else
                        {
                            newfiletitle = (options.UseOriginalFilenames) ? Path.GetFileNameWithoutExtension(item.FullFileName) : ProcessTags(options.MovieFileTemplate, item.MovieDetail);
                            fullpath = Path.GetDirectoryName(item.FullFileName);
                            newxmlfilename = fullpath + Path.DirectorySeparatorChar + RemoveIllegalPathCharacters(newfiletitle) + ".xml";
                        }
                    }
                    else
                    {
                        newfiletitle = (options.UseOriginalFilenames) ? Path.GetFileNameWithoutExtension(item.FullFileName) : ProcessTags(options.TVFileTemplate, item.SeriesName, item.Season, item.Episode, item.EpisodeName, new DateTime());
                        fullpath = Path.GetDirectoryName(item.FullFileName);
                        newxmlfilename = fullpath + Path.DirectorySeparatorChar + RemoveIllegalPathCharacters(newfiletitle) + ".xml";

                    }
                    // do some screen updates...
                    sbStatus.Text = string.Format("Saving {0} to file {1}", newfiletitle, newxmlfilename);
                    Application.DoEvents();

                    var fs = new FileStream(newxmlfilename, FileMode.Create);
                    TextWriter writer = new StreamWriter(fs, new UTF8Encoding());
                    var x = new XmlSerializer(md.GetType());
                    // Serialize using the XmlTextWriter.
                    var xmlnsEmpty = new XmlSerializerNamespaces();
                    xmlnsEmpty.Add(string.Empty, string.Empty);
                    // Serialize using the XmlTextWriter.
                    x.Serialize(writer, md, xmlnsEmpty);
                    writer.Close();

                    if (options.SavePictureWithMetadata)
                    {
                        // WRite out the thumbnail
                        string newthumbfilename = fullpath + Path.DirectorySeparatorChar + RemoveIllegalPathCharacters(newfiletitle) + ".jpg";
                        if (item.VideoType == VideoTypeEnum.MovieType)
                        {
                            var webclient = new WebClient();
                            webclient.DownloadFile(thumbnailurl, newthumbfilename);
                            if (userImage)
                            {
                                ResizeInternetImage(thumbnailurl, newthumbfilename, 0, false, "");
                                userImage = false;
                            }
                        }
                        else
                        {
                            ResizeInternetImage(thumbnailurl, newthumbfilename, item.Episode,
                                           (thumbnailurl == "nothumb.jpg"), item.SeriesName);
                            string folderfilename = fullpath + Path.DirectorySeparatorChar + "folder.jpg";
                            ResizeInternetImage(thumbnailurl, folderfilename, 0, (thumbnailurl == "nothumb.jpg"), item.SeriesName);
                            if (!File.Exists(folderfilename)) File.Copy(newthumbfilename, folderfilename, true);
                        }
                        item.ThumbnailPresent = true;
                        item.ThumbPath = newthumbfilename;
                    }
                    else
                    {
                        item.ThumbnailPresent = false;
                        item.ThumbPath = string.Empty;
                    }

                    if (!item.VOBDirectory)
                    {
                        // rename the original file last of all to this new name...
                       
                        // This is all unnecessary if options.UseOriginalFilenames is set
                        if (!options.UseOriginalFilenames)
                        {
                            string oldfilename = item.FullFileName;
                            string newfilename = fullpath + Path.DirectorySeparatorChar +
                                                 RemoveIllegalPathCharacters(newfiletitle) +
                                                 Path.GetExtension(item.FullFileName);

                            File.Move(oldfilename, newfilename);

                        }
                        // Now deal with Subs, there are no subs in a vob directory
                        if (item.SubsPresent)
                            RenameSubFiles(item.FullFileName, newfiletitle);
                    }
                    else
                    {
                        // Now deal with subs...
                        if (item.SubsPresent)
                            RenameSubFiles(item.FullFileName, newfiletitle);
                    }
                    sbStatus.Text = "Done!";

                    item.XmlPresent = true;
                    item.UpdateProcessedDate();
                    objectListViewMovie.OwnerDraw = true;
                    //objectListViewMovie.SetObjects(movieList);
                    objectListViewMovie.RefreshObject(movieList[0]);
                    Cursor.Current = Cursors.Default;
                    Application.DoEvents();
                }
                catch (Exception ex)
                {
                    //sbStatus.Text = string.Format("Message:{0}\nStack Trace:{1}", ex.Message, ex.StackTrace);
                    ExceptionHandler(ex, "SaveCurrentItem Movie");
                    Cursor.Current = Cursors.Default;
                }


                movieNumToShow = 0;
                return true;
            }
            return false;
        }

        /*  private bool SaveCurrentItem(VideoItem item) // int index)
          {
              if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In SaveCurrentItem");
              //OLVSelectedIndex = index;
              details md = item.MovieDetail;

              Cursor.Current = Cursors.WaitCursor;

              if (md != null)
              {
                  // get the correct sized picture

                  string thumbnailurl = pbTV.ImageLocation;

                  try
                  {
                      //string newfilename = ProcessTags(options.TVFileTemplate,item.)
                      string newtemplatefilename = ProcessTags(options.TVFileTemplate, item.SeriesName,item.Season,item.Episode,item.EpisodeName,new DateTime());
                      string fullpath = Path.GetDirectoryName(item.FullFileName);
                      string newxmlfilename = fullpath + Path.DirectorySeparatorChar + RemoveIllegalPathCharacters(newtemplatefilename) + ".xml";
                      sbStatus.Text = string.Format("Saving {0} to file {1}", newtemplatefilename, newxmlfilename);
                      Application.DoEvents();
                    

                      var fs = new FileStream(newxmlfilename, FileMode.Create);
                      TextWriter writer = new StreamWriter(fs, new UTF8Encoding());
                      var x =
                          new XmlSerializer(md.GetType());
                      // Serialize using the XmlTextWriter.
                      var xmlnsEmpty = new XmlSerializerNamespaces();
                      xmlnsEmpty.Add("", "");
                      // Serialize using the XmlTextWriter.
                      x.Serialize(writer, md, xmlnsEmpty);

                      writer.Close();

                      // rename the original file last of all to this new name...
                      string oldfilename = item.FullFileName;
                      string newfilename = fullpath + Path.DirectorySeparatorChar + RemoveIllegalPathCharacters(newtemplatefilename) +
                                           Path.GetExtension(item.FullFileName);
                      File.Move(oldfilename, newfilename);

                      if (options.SavePictureWithMetadata)
                      {
                          // WRite out the thumbnail
                          string newthumbfilename = fullpath + Path.DirectorySeparatorChar +
                                                    RemoveIllegalPathCharacters(newtemplatefilename) + ".jpg";
                        
                          ResizeInternetImage(thumbnailurl, newthumbfilename, item.Episode,
                                              (thumbnailurl == "nothumb.jpg"), item.SeriesName);
                          //webclient.DownloadFile(thumbnailurl, newthumbfilename);
                          string folderfilename = fullpath + Path.DirectorySeparatorChar + "folder.jpg";
                          ResizeInternetImage(thumbnailurl, folderfilename, 0, (thumbnailurl == "nothumb.jpg"), item.SeriesName);
                          if (!File.Exists(folderfilename)) File.Copy(newthumbfilename, folderfilename, true);
                          item.ThumbnailPresent = true;
                          item.ThumbPath = newthumbfilename;
                      }
                      else
                      {
                          item.ThumbnailPresent = false;
                          item.ThumbPath = string.Empty;
                      }
                      // Now deal with subs...
                      if (item.SubsPresent)
                          RenameSubFiles(item.FullFileName, newtemplatefilename);

                      sbStatus.Text = "Done!";
                      item.XmlPresent = true;
                      item.UpdateProcessedDate();
                      objectListViewTV.OwnerDraw = true;
                      objectListViewTV.SetObjects(tvList);

                      Cursor.Current = Cursors.Default;
                      Application.DoEvents();
                  }
                  catch (Exception ex)
                  {
                      //sbStatus.Text = string.Format("Message:{0}\nStack Trace:{1}", ex.Message, ex.StackTrace);
                      ExceptionHandler(ex,"SaveCurrentItem TV");
                      Cursor.Current = Cursors.Default;
                  }


                  movieNumToShow = 0;
                  return true;
              }
              return false;
          }

          */

        private void btnProcessAlternate_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnProcessAlternate_Click");
            // save the existing one...
            if (objectListViewMovie.SelectedIndex > -1)
            {
                SaveCurrentItem((VideoItem)objectListViewMovie.SelectedObject);

            }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnPrev_Click");
            if (movieNumToShow > 0)
            {
                movieNumToShow--;
                var item = (VideoItem)objectListViewMovie.SelectedObject;
                ShowDetailsOnCurrentOLVItem(item);
            }
        }


        private void btnNextImage_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnNextImage_Click");
            if (pictureBox1.Tag.ToString() != "")
            {
                if (objectListViewMovie.SelectedObject != null)
                {
                    VideoItem item = (VideoItem)objectListViewMovie.SelectedObject;
                    switch (item.VideoType)
                    {
                        case VideoTypeEnum.MovieType:
                            LoadNextPicture(pictureBox1);
                            break;
                        case VideoTypeEnum.TVType:
                            LoadNextTVPicture(pictureBox1);
                            break;
                        case VideoTypeEnum.AdultType:
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }

                }
            }
        }

        #endregion

        public frmMainForm()
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In frmMainForm");
            InitializeComponent();
            m_cacheProvider = mCacheProvider;
        }

        

        private IEnumerable<string> GetReplacements()
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In GetReplacements");
            string ve = options.RemoveWords;
            return ve.Split(',').ToList();
        }
        private IEnumerable<string> GetSubstitutions()
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In GetSubstitutions");
            string ve = options.Substitutions;
            return ve.Split(',').ToList();
        }

        /*    private void btnGetShows_Click(object sender, EventArgs e)
            {
                if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnGetShows_Click");
                // Check to make sure that the text path exists before starting....
                if (Directory.Exists(txtSeriesPath.Text))
                {

                    seriesNumToShow = 0;
                    m_tvdbHandler = new TvdbHandler(m_cacheProvider, "BEBB657E228E2DD7");
                        // File.ReadAllText("api_key.txt"));
                    // PopulateList(txtSeriesPath.Text, chkGroupByProcessedTV.Checked,lvwTVFileList,showtype.tv);

                    LoadTVShowList(txtSeriesPath.Text);
                    //LoadMovieList(txtPath.Text);
                    objectListViewTV.OwnerDraw = true;
                    objectListViewTV.SetObjects(tvList);
                }
                else
                {
                    txtSeriesPath.ForeColor = Color.Red;
                    btnGetShows.Enabled = false;
                    sbStatus.Text = string.Format("TV Show Directory: {0} does not exist, please choose a valid directory",
                                                  txtSeriesPath.Text);
                }
            } */

        /*   private void LoadTVShowList(string path)
           {
               if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadTVShowList");
               // clear the existing movielist first.
               tvList.Clear();
               olvcXMLPresentTV.GroupKeyToTitleConverter = delegate(object key)
                                                               {
                                                                   if (key.ToString() == "True")
                                                                       return ("Processing Complete");
                                                                   return ("Not Processed");
                                                               };

               olvcThumbPresentTV.GroupKeyToTitleConverter = delegate(object key)
                                                                 {
                                                                     if (key.ToString() == "True")
                                                                         return ("Processing Complete");
                                                                     return ("Not Processed");
                                                                 };
               objectListViewTV.PrimarySortColumn = olvcXMLPresentTV;

               objectListViewTV.UseTranslucentHotItem = options.ShowCards;

               // Make the hot item show an overlay when it changes
               objectListViewTV.HotItemStyle.Overlay = new TVCardOverlay();
               objectListViewTV.HotItemStyle = this.objectListViewTV.HotItemStyle;

               Cursor = Cursors.WaitCursor;
               sbStatus.Text = string.Format("Loading TV Shows from Directory {1}{0}", path,
                                             (options.RecursiveSearch) ? "(and subfolders) " : "");

               Application.DoEvents();  // Allow this to be displayed...

               string[] filelist = Directory.GetFiles(path, "*.*",  (options.RecursiveSearch)? SearchOption.AllDirectories:SearchOption.TopDirectoryOnly);
               validExtensions = GetValidExtensions();

               int fileTotal = filelist.Length;
               int fileCount = 0;
               int foundcount = 0;
               int ignorecount = 0;
               int foundnewcount = 0;

               sbProgress.Maximum = fileTotal+1;
               sbProgress.Value = 0;

               foreach (string filename in filelist)
               {
                   sbStatus.Text = string.Format("Processing {0} of {1} Files", fileCount++, fileTotal);
                   sbProgress.Value = fileCount;
                   Application.DoEvents();
                
                   if (validExtensions.Contains(Path.GetExtension(filename).ToLower()))
                   {
                       foundcount++;
                       // i have a movie file... now I need to see if that movie file has an xml associated with it.
                       bool XMLProcessed = File.Exists(Path.ChangeExtension(filename, "xml"));
                       bool JPGProcessed = File.Exists(Path.ChangeExtension(filename, "jpg"));
                       bool SubsPresent = SubPresent(filename);

                       //string seasonEpisode;
                       string seasonEpisode = GetEpisodeSeason(CleanFileName(GetFileNameWithoutExtensionFast(filename)));
                       bool skipprocessing = (seasonEpisode == string.Empty);

                       if (!skipprocessing)
                       {

                           if (XMLProcessed)
                           {
                               string fullpath = Path.GetDirectoryName(filename);
                               string strippedfilename = Path.GetFileNameWithoutExtension(filename);
                               string imagelocation = JPGProcessed ? Path.ChangeExtension(filename, "jpg") : "notfound.jpg";
                               var movieDetails = new details();
                               string newxmlfilename = fullpath + Path.DirectorySeparatorChar + strippedfilename + ".xml";
                               movieDetails = DeserializeDetails(newxmlfilename);
                               seasonEpisode = GetEpisodeSeason(filename);
                               var VideoItem = new VideoItem(movieDetails.title, movieDetails.overview, filename,
                                                       Convert.ToInt32(seasonEpisode.Split(':')[0]),
                                                       Convert.ToInt32(seasonEpisode.Split(':')[1]),
                                                       imagelocation, true, true, SubsPresent, movieDetails.title,
                                                       movieDetails);
                               tvList.Add(VideoItem);
                           }
                           else // no movie xml file found, so I need to parse the name and load it in the tvList anyway
                           {
                               seasonEpisode = GetEpisodeSeason(filename);
                               if (seasonEpisode != string.Empty)
                               {
                                   string cleanfilename = CleanFileName(GetFileNameWithoutExtensionFast(filename));
                                   cleanfilename = RemoveEpisodeInformation(cleanfilename).Trim();

                                   // deal with tv shows that rely on the directory to have name of show
                                   if (cleanfilename.Trim()==string.Empty)
                                   {
                                       cleanfilename = Directory.GetParent(filename).Name;
                                       if (cleanfilename.ToLower().StartsWith("season"))
                                       {   
                                           cleanfilename = Directory.GetParent(filename).FullName;
                                           cleanfilename = Directory.GetParent(cleanfilename).Name;
                                       }

                                   }

                                   // cleanfilename = cleanfilename.Replace(seasonEpisode)
                                   var VideoItem = new VideoItem(cleanfilename, filename,
                                                           Convert.ToInt32(seasonEpisode.Split(':')[0]),
                                                           Convert.ToInt32(seasonEpisode.Split(':')[1]), false, false,
                                                           SubsPresent);
                                   tvList.Add(VideoItem);
                                   foundnewcount++;
                               }
                               else ignorecount++;
                           }
                       }
                   }
               }
               // finished....
               Cursor = Cursors.Default;
               sbProgress.Value = 0;
               sbStatus.Text = string.Format("Done! Processed {0} shows, {2} New, {3} Ignored . Subfolders {1}searched",
                                             foundcount,
                                             (options.RecursiveSearch) ? string.Empty : "not ", foundnewcount, ignorecount);

           } */

        private string GetEpisodeSeason(string filename)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In GetEpisodeSeason");
            string returnvalue = string.Empty;
            Match seasonepisodematch = GetSEString(GetFileNameWithoutExtensionFast(filename));
            if (seasonepisodematch != null)
            {
                if (seasonepisodematch.Groups["combined"].Success)
                {

                    string combined = seasonepisodematch.Groups["combined"].Value;
                    string seasonstring = (combined.Length > 3)
                                              ? combined.Substring(0, 2)
                                              : combined.Substring(0, 1);
                    if (Convert.ToInt32(seasonstring) > 18) return string.Empty;  // keeps dates from being strings... and really 19 seasons? only teh simpsons...
                    //item.SubItems.Add(seasonstring);
                    string epstring = (combined.Length > 3)
                                          ? combined.Substring(2, 2)
                                          : combined.Substring(1, 2);
                    //item.SubItems.Add(epstring);
                    returnvalue = string.Format("{0}:{1}", seasonstring, epstring);
                }
                else
                {
                    returnvalue = string.Format("{0}:{1}", seasonepisodematch.Groups["season"].Value,
                                                seasonepisodematch.Groups["episode"].Value);
                }
            }
            return returnvalue;
        }


        private details LoadTheDetails(TvdbSeries ser, string seriesfilename, int SNum, int EpNum)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadTheDetails");
            var md = new details();
            int catcount = 0;
            int currentactor = 0;

            try
            {
                var actors = new detailsActor[ser.TvdbActors.Count];
                foreach (TvdbActor tvactor in ser.TvdbActors)
                {
                    var actor = new detailsActor { name = tvactor.Name, role = tvactor.Role };
                    actors[currentactor] = new detailsActor();
                    actors[currentactor] = actor;
                    currentactor++;
                }

                md.actor = actors;

                var cats = new detailsGenre[ser.Genre.Count];
                foreach (string category in ser.Genre)
                {
                    var cat = new detailsGenre { Value = category };
                    cats[catcount] = new detailsGenre();
                    cats[catcount] = cat;
                    catcount++;
                }
                md.genre = cats;

                md.mpaa = ser.ContentRating;
                md.overview =  ser.Overview;  // JAG
                md.plot = ser.Overview;
                md.prevgenre = "N/A";
                md.prevtitle = Path.GetFileName(seriesfilename);
                md.rating = ser.Rating.ToString();
                /*runtime*/
                //md.runtime = ser.Runtime.ToString();
                // md.runtime = options.RunTimeFormat == "hours and minutes" ? string.Format("{0}h{1}m", ser.Runtime /(int) 60, movie.Runtime.Minutes) : string.Format("{0}", movie.Runtime.TotalMinutes);
                int runtimetotalmins = Convert.ToInt32(ser.Runtime);
                int runtimehours = runtimetotalmins / 60;
                int runtimemins = runtimetotalmins - (60 * runtimehours);
                md.runtime = options.RunTimeFormat == "hours and minutes" ? string.Format("{0}h {1}", runtimehours, runtimemins) : string.Format("{0}", runtimetotalmins);
               
                md.studio = ser.Network;
                int backdropcount = 1;
                //detailsThumbnail[] thumbs = new detailsThumbnail[thumbnailcount];
                var backs = new detailsBackdrop[backdropcount];
                int bdcount = 0;

//                if (SNum == 0)
//                {
//                    md.title = ser.SeriesName.Replace(':', '-');
//                    md.overview = ser.Overview; //JAG
//                    backs[bdcount] = new detailsBackdrop();
//                    backs[bdcount].Value = TvdbLinkCreator.CreateBannerLink(ser.BannerPath);
//                    //var thumbs = new detailsThumbnail[thumbnailcount];
//                    md.backdrop = backs;
//                }
//                else
 //               {
                    foreach (TvdbEpisode episode in ser.Episodes)
                    {
                        if ((episode.SeasonNumber == Convert.ToInt32(SNum)) &&
                            (episode.EpisodeNumber == Convert.ToInt32(EpNum)))
                        {
                            md.title = ProcessTags(options.TVTitleTemplate, ser.SeriesName, SNum, EpNum, episode.EpisodeName, ser.FirstAired);
                            // md.title = string.Format("{0} [{1:00}x{2:00}] {3}", ser.SeriesName.Replace(':', '-'), SNum, EpNum,
                            //                          episode.EpisodeName.Replace('?', '.').Replace('\\',' ').Replace('/',' '));
                            //md.overview = episode.Overview;  // JAG
                            md.overview = GenerateDescriptionFromTemplate(ser, episode);
                            md.plot = md.overview;

                            md.year = string.Format("{0}-{1:00}-{2:00}", episode.FirstAired.Year,
                                                    episode.FirstAired.Month,
                                                    episode.FirstAired.Day);
                            md.firstaired = md.year;
                            backs[bdcount] = new detailsBackdrop
                                                 {
                                                     Value = TvdbLinkCreator.CreateBannerLink(episode.BannerPath)
                                                 };
                            bdcount++;
                            break;
                        }
                    }

                    int tcount = 0;
                    int thumbnailcount = ser.SeasonBanners.Count(image => image.Season == Convert.ToInt32(SNum));
                    var thumbs = new detailsThumbnail[thumbnailcount];
                    foreach (TvdbSeasonBanner image in ser.SeasonBanners)
                    {
                        if (image.Season == Convert.ToInt32(SNum))
                        {
                            thumbs[tcount] = new detailsThumbnail
                                                 {
                                                     Value = TvdbLinkCreator.CreateBannerLink(image.BannerPath)
                                                 };
                            tcount++;
                        }
                    }
                    //md.backdrop = backs;
                    md.backdrop = options.SaveBackdrops ? backs : null;
                    md.thumbnail = thumbs;
            //    }


                md.trailer = "N/A";

                md.url = new detailsUrl[1];
                var urls = new detailsUrl[1];
                urls[0] = new detailsUrl { cache = "tmdb-.xml", function = "GetTMDBThumbsById" };
                md.url = urls;
                //md.year = ser.FirstAired.ToShortDateString();
                
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
            return md;
        }

        private string GenerateDescriptionFromTemplate(TvdbSeries ser, TvdbEpisode episode)
        {
            string returnString = options.DescriptionTemplate;
            // Use a regular expression to find all of the tags, then replace them with real values.. for reals..
            // "[%SeriesName%] [[%SeasonNumber%]x[%EpisodeNumber%]] - [%EpisodeName%]"

            Regex regex = new Regex(@"(\[%\w+%\])", RegexOptions.IgnoreCase);

            MatchCollection matches = regex.Matches(options.DescriptionTemplate);

            foreach (Match match in matches)
            {
                switch (match.Value)
                {
                    case "[%Description%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(episode.Overview));
                        break;
                    case "[%Rating%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(ser.Rating.ToString()));
                        break;
                    case "[%MPAA%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(ser.ContentRating ));
                        break;
                    case "[%Season%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0:0}", episode.SeasonNumber));
                        break;
                    case "[%EpisodeNumberNoZero%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0:0}", episode.EpisodeNumber));
                        break;
                    case "[%EpisodeName%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(episode.EpisodeName));
                        break;
                    case "[%Year%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0}", episode.FirstAired.Year));
                        break;
                    case "[%RunTime%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0}", options.RunTimeFormat == "hours and minutes" ? string.Format("{0}h{1}m", episode.FirstAired.Hour, episode.FirstAired.Minute) : string.Format("{0}", episode.FirstAired.Minute)));
                        break;
                }
            }
            return returnString;
        }

        private string GenerateDescriptionFromTemplate(TmdbMovie mov)
        {
            string returnString = options.DescriptionTemplate;

            // Use a regular expression to find all of the tags, then replace them with real values.. for reals..
            // "[%SeriesName%] [[%SeasonNumber%]x[%EpisodeNumber%]] - [%EpisodeName%]"

            Regex regex = new Regex(@"(\[%\w+%\])", RegexOptions.IgnoreCase);

            MatchCollection matches = regex.Matches(options.DescriptionTemplate);

            foreach (Match match in matches)
            {
                switch (match.Value)
                {
                    case "[%Description%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(mov.overview));
                        break;
                    case "[%MPAA%]":  // replace all of the spaces anywhere in teh file with dots... at this point.
                         TmdbMovieReleases release = api.GetMovieReleases(movie.id);
                        string mpaa = null;
                foreach (ReleaseCountry country in release.countries)
                {
                     mpaa = country.certification;

                }
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(mpaa));
                        break;
                    case "[%Rating%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(mov.vote_average.ToString()));
                        break;
                    case "[%Year%]":
                        // Conver the year string into a real year number.
                        DateTime movieyear = DateTime.Parse(mov.release_date);
                        returnString = returnString.Replace(match.Value, string.Format("{0}", movieyear.Year));
                        break;
                    case "[%RunTime%]":
                        int hours = Convert.ToInt32(mov.runtime)/60;
                        int minutes = Convert.ToInt32(mov.runtime) % 60;
 /*runtime*/                     //  returnString = returnString.Replace(match.Value, mov.runtime + " minutes"); // 
 returnString = string.Format("{0}",options.RunTimeFormat == "hours and minutes" ? string.Format("{0}h{1}m", hours,minutes) : string.Format("{0}m", mov.runtime) );
                        break;
                }
            }
            return returnString;
        }

        //private string ProcessTags(string tvTitleTemplate, TvdbSeries ser, TvdbEpisode episode)
        //ProcessTags(options.TVTitleTemplate, ser.SeriesName, SNum,EpNum,episode.EpisodeName,ser.FirstAired);
        private string ProcessTags(string tvTitleTemplate, string seriesname, int seasonNum, int episodeNum, string episodeName, DateTime firstaired)
        {
            string returnString = tvTitleTemplate;

            // Use a regular expression to find all of the tags, then replace them with real values.. for reals..
            // "[%SeriesName%] [[%SeasonNumber%]x[%EpisodeNumber%]] - [%EpisodeName%]"

            Regex regex = new Regex(@"(\[%\w+%\])", RegexOptions.IgnoreCase);

            MatchCollection matches = regex.Matches(tvTitleTemplate);

            foreach (Match match in matches)
            {
                switch (match.Value)
                {
                    case "[%SeriesName%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(seriesname));
                        break;
                    case "[%SeasonNumber%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0:00}", seasonNum));
                        break;
                    case "[%EpisodeNumber%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0:00}", episodeNum));
                        break;
                    case "[%SeasonNumberNoZero%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0:0}", seasonNum));
                        break;
                    case "[%EpisodeNumberNoZero%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0:0}", episodeNum));
                        break;
                    case "[%EpisodeName%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(episodeName));
                        break;
                    case "[%Dots%]":  // replace all of the spaces anywhere in teh file with dots... at this point.
                        returnString = returnString.Replace(match.Value, string.Empty); // remove the tag first...
                        returnString = returnString.Replace(' ', '.'); // replaces all spaces with dots...
                        break;
                    case "[%UnderLines%]":
                        returnString = returnString.Replace(match.Value, string.Empty); // remove the tag first...
                        returnString = returnString.Replace(' ', '_');
                        break;
                    case "[%Year%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0}", firstaired.Year));
                        break;
                    case "[%RunTime%]":
                        returnString = returnString.Replace(match.Value, string.Format("{0}", options.RunTimeFormat == "hours and minutes" ? string.Format("{0}h{1}m", firstaired.Hour, firstaired.Minute) : string.Format("{0}", firstaired.Minute)));
                        break;
                }
            }
            // remove special characters if they exist.
            foreach (string s in options.SpecialCharacters.Split(','))
            {
                returnString = returnString.Replace(s.Split('=')[0], s.Split('=')[1]);
            }
            return returnString;
        }

        private string ProcessTags(string movieTitleTemplate, details moviedetails)
        {
            string returnString = movieTitleTemplate;

            // Use a regular expression to find all of the tags, then replace them with real values.. for reals..
            // "[%SeriesName%] [[%SeasonNumber%]x[%EpisodeNumber%]] - [%EpisodeName%]"

            Regex regex = new Regex(@"(\[%\w+%\])", RegexOptions.IgnoreCase);

            MatchCollection matches = regex.Matches(movieTitleTemplate);

            foreach (Match match in matches)
            {
                switch (match.Value)
                {
                    case "[%MovieName%]":
                        returnString = returnString.Replace(match.Value, RemoveIllegalPathCharacters(moviedetails.title));
                        break;
                    case "[%Dots%]":  // replace all of the spaces anywhere in teh file with dots... at this point.
                        returnString = returnString.Replace(match.Value, string.Empty); // remove the tag first...
                        returnString = returnString.Replace(' ', '.'); // replaces all spaces with dots...
                        break;
                    case "[%UnderLines%]":
                        returnString = returnString.Replace(match.Value, string.Empty); // remove the tag first...
                        returnString = returnString.Replace(' ', '_');
                        break;
                    case "[%Year%]":
                        // Conver the year string into a real year number.
                        DateTime movieyear = Convert.ToDateTime(moviedetails.year);
                        returnString = returnString.Replace(match.Value, string.Format("{0}", movieyear.Year));
                        break;
                    case "[%RunTime%]":
                        int hours = Convert.ToInt32(moviedetails.runtime)/60;
                        int minutes = Convert.ToInt32(moviedetails.runtime) % 60;
  /*runtime*/                     // returnString = returnString.Replace(match.Value, moviedetails.runtime + " minutes"); // 
  returnString = string.Format("{0}",options.RunTimeFormat == "hours and minutes" ? string.Format("{0}h{1}m", hours,minutes) : string.Format("{0}m", moviedetails.runtime) );
                        break;
                }
            }
            // remove special characters if they exist.
            foreach (string s in options.SpecialCharacters.Split(','))
            {
                returnString = returnString.Replace(s.Split('=')[0], s.Split('=')[1]);
            }
            return returnString;
        }


        private void btnTVSaveThisOne_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnTVSaveThisOne_Click");
            // save the existing one...
            if (objectListViewTV.SelectedIndex > -1)
            {
                SaveCurrentItem((VideoItem)objectListViewTV.SelectedObject);
            }
        }

        private Image resizeImage(Image imgToResize, Size size, int number, bool empty, string seriesName)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In resizeImage");
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercentW = (size.Width / (float)sourceWidth);
            float nPercentH = (size.Height / (float)sourceHeight);

            float nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;

            var destWidth = (int)(sourceWidth * nPercent);
            var destHeight = (int)(sourceHeight * nPercent);
            //lblMovieTitle.Text = videoItem.VideoDetails.title;
            var b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);

            if ((number > 0) && (options.NumberOnShow)) 
            {
                StringFormat strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Far;
                strFormat.LineAlignment = StringAlignment.Far;
                g.DrawString(number.ToString(), new Font("Tahoma", 64), Brushes.DarkGray,
                    new RectangleF(0, 0, destWidth + 5, destHeight + 5), strFormat);
                g.DrawString(number.ToString(), new Font("Tahoma", 64), Brushes.White,
                    new RectangleF(0, 0, destWidth, destHeight), strFormat);

            }
            if (empty)
            {
                seriesName = "\n" + seriesName;
                StringFormat strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Center;
                strFormat.LineAlignment = StringAlignment.Near;
                g.DrawString(seriesName, new Font("Tahoma", 14), Brushes.LightGray,
                    new RectangleF(0, 0, destWidth + 1, destHeight + 1), strFormat);
                g.DrawString(seriesName, new Font("Tahoma", 14), Brushes.White,
                    new RectangleF(0, 0, destWidth, destHeight), strFormat);
            }

            g.Dispose();

            return b;
        }


        private void btnChangePath_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnChangePath_Click");
            folderBrowserDialog1.SelectedPath = txtSeriesPath.Text;
            if (folderBrowserDialog1.ShowDialog() != DialogResult.Cancel)
            {
                txtSeriesPath.Text = folderBrowserDialog1.SelectedPath;
                options.TVShowDirectory = txtSeriesPath.Text;
                options.SaveSettings();
                txtSeriesPath.ForeColor = SystemColors.WindowText;
                btnGetShows.Enabled = true;
                sbStatus.Text = "";
            }
        }

        private void btnTVSelectAll_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnTVSelectAll_Click");
            int noXMl = tvList.Count(item => !item.XmlPresent);
            Cursor = Cursors.WaitCursor;
            // Count the number of unchecked items..
            sbProgress.Maximum = noXMl;
            sbProgress.Value = 0;
            InAutomationLoop = true;

            // int index = 0;
            int moviesUpdated = 0;

            foreach (VideoItem item in tvList)
            {
                if (!item.XmlPresent)
                {
                    //OLVSelectedIndex = index;
                    ShowDetailsOnCurrentOLVItem(item); // OLVSelectedIndex);
                    if (SaveCurrentItem(item)) moviesUpdated++;
                    sbStatus.Text = string.Format("Processing {0} of {1} Shows ", moviesUpdated, noXMl);
                    sbProgress.Value++;
                    Application.DoEvents();
                }
                //   index++;
            }

            sbProgress.Value = 0;
            sbStatus.Text = string.Format("Done Processing {0} Shows, {1} Saved. {2} Errors", noXMl, moviesUpdated,
                                          noXMl - moviesUpdated);
            Cursor = Cursors.Default;
            InAutomationLoop = false;
        }


        /*  private void lvwTVFileList_DoubleClick(object sender, EventArgs e)
          {
              if (allowlookup)
              {
                  //if (lvwTVFileList.SelectedItems.Count>0)

                  //    ShowDetailsOnCurrentVideoItem(lvwTVFileList.SelectedItems[0], false);
              }
          } */



        private void deleteFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In deleteFileToolStripMenuItem_Click");
            if (tabControl1.SelectedTab.Name == "tabMovies")
            {
                if (objectListViewMovie.SelectedIndex > -1)
                {
                    var item = (VideoItem)objectListViewMovie.SelectedObject;
                    if (
                        MessageBox.Show(string.Format("Delete {0} permanently?", item.FullFileName), "Delete File?",
                                        MessageBoxButtons.YesNo) == DialogResult.Yes)
                        File.Delete(item.FullFileName);
                    LoadVideoList(cboPath.Text);
                    objectListViewMovie.OwnerDraw = true;
                    objectListViewMovie.SetObjects(movieList);
                }
            }
            /* else
             {
                 if (objectListViewTV.SelectedIndex > -1)
                 {
                     var item = (VideoItem) objectListViewTV.SelectedObject;
                     if (
                         MessageBox.Show(string.Format("Delete {0} permanently?", item.FullFileName), "Delete File?",
                                         MessageBoxButtons.YesNo) == DialogResult.Yes)
                         File.Delete(item.FullFileName);
                     LoadTVShowList(txtSeriesPath.Text);
                     objectListViewTV.OwnerDraw = true;
                     objectListViewTV.SetObjects(tvList);
                 }
             } */
        }

        private void renameFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In renameFileToolStripMenuItem_Click");
            if (tabControl1.SelectedTab.Name == "tabMovies")
            {
                // put a text box over the appropriate subitem with the text in it...
                if (objectListViewMovie.SelectedIndex > -1)
                {
                    var item = (VideoItem)objectListViewMovie.SelectedObject;

                    btnRenameFile.Visible = true;
                    txtRenameFile.Visible = true;
                    btnCancelRename.Visible = true;
                    txtRenameFile.Text = item.FullFileName;
                    txtRenameFile.Tag = item;
                }
            }
            /*    else
                {
                    if (objectListViewTV.SelectedIndex > -1)
                    {
                        var item = (VideoItem) objectListViewTV.SelectedObject;

                        btnRenameTV.Visible = true;
                        txtRenameTV.Visible = true;
                        btnCancelRenameTV.Visible = true;
                        txtRenameTV.Text = item.FullFileName;
                        txtRenameTV.Tag = item;
                    }
                } */
        }

        private void btnRenameFile_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnRenameFile_Click");
            if (txtRenameFile.Tag != null)
            {
                VideoItem item = (VideoItem)txtRenameFile.Tag;
                //txtRenameFile.Text =  txtRenameFile.Text));
                txtRenameFile.Text = Path.GetDirectoryName(txtRenameFile.Text) + Path.DirectorySeparatorChar +
                                     RemoveIllegalPathCharacters(Path.GetFileName(txtRenameFile.Text));
                File.Move(item.FullFileName, txtRenameFile.Text);
                item.FullFileName = txtRenameFile.Text;
                item.CleanFileName = CleanFileName(Path.GetFileNameWithoutExtension(item.FullFileName));
                btnRenameFile.Visible = false;
                btnCancelRename.Visible = false;
                txtRenameFile.Visible = false;
            }
            //PopulateList(txtPath.Text, chkShowUnprocessed.Checked, lvwFileList, showtype.movie);
        }

        private void btnCancelRename_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnCancelRename_Click");
            btnRenameFile.Visible = false;
            btnCancelRename.Visible = false;
            txtRenameFile.Visible = false;
        }

        private void btnSeasonInfo_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnSeasonInfo_Click");
            // assume you are in a season directory...
            if (series.Banners.Count > 0)
            {
                //TvdbSeries ser = series;
                // get the "poster banners" and put the first on in a "folder.jpg" in the series folder...
                TvdbPosterBanner posterBanner = series.PosterBanners[0];

                // Prompt for the folder here
                folderBrowserDialog1.SelectedPath = txtSeriesPath.Text;
                folderBrowserDialog1.Description = "Choose where you want the season folder icon stored.";
                if (folderBrowserDialog1.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
                {
                    string folderfilename = folderBrowserDialog1.SelectedPath + Path.DirectorySeparatorChar + "folder.jpg";
                    //PictureBox tempimage = new PictureBox();
                    string fileuri = TvdbLinkCreator.CreateBannerLink(posterBanner.BannerPath);
                    // wait for picture box to load the image...
                    ResizeInternetImage(fileuri, folderfilename, 0, false, string.Empty);
                    MessageBox.Show("Press Ok to Continue", "Folder Icon Successfully saved");
                }
            }
        }

        private void ResizeInternetImage(string fileuri, string folderfilename, int number, bool empty, string seriesName)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In ResizeInternetImage");
            var webClient = new WebClient();
            // load the fileuri from the web into  an image for resize. no temp file please ....
            byte[] imageData = webClient.DownloadData(fileuri); //DownloadData function from here
            var stream = new MemoryStream(imageData);
            Image thumbnailimage = Image.FromStream(stream);
            stream.Close();

            thumbnailimage = resizeImage(thumbnailimage, new Size(185, 278), number, empty, seriesName);
            thumbnailimage.Save(folderfilename, ImageFormat.Jpeg);
        }

        private void lookupInformationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In lookupInformationToolStripMenuItem_Click");
            if (tabControl1.SelectedTab.Name == "tabMovies")
            {
                // look up the currently selected Movie information and display on the screen
                // Get the currently selected item under the cursor...
                if (objectListViewMovie.SelectedItems.Count > 0)
                {
                    ShowDetailsOnCurrentOLVItem((VideoItem)objectListViewMovie.SelectedObject);
                    // objectListViewMovie.SelectedIndex);
                }
            }
            else
            {
                if (objectListViewTV.SelectedItems.Count > 0)
                {
                    ShowDetailsOnCurrentOLVItem((VideoItem)objectListViewTV.SelectedObject);
                    // objectListViewMovie.SelectedIndex);
                }
            }
        }

        /* private void ShowDetailsOnCurrentOLVItemWithXML(VideoItem item)
         {
             if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In ShowDetailsOnCurrentOLVItemWithXML");
             //pbWaiting.Visible = true;
             pbTV.Image = null;
             flowLayoutPanel2.Controls.Clear();
             Application.DoEvents(); // allow the animated gif to show up...

             if (item.XmlPresent)
             {
                 details movieDetails = item.MovieDetail;
                 // get the correct sized picture
                 LoadPictureBox(pbTV,Path.GetDirectoryName(item.FullFileName)+ Path.DirectorySeparatorChar + Path.ChangeExtension(RemoveIllegalPathCharacters( Path.GetFileName(item.FullFileName) ), ".jpg"));
                 if (pbTV.Tag == null) btnNextImage.Enabled = false;
                 btnShowMoreSeries.Enabled = false;
                 btnTVSaveThisOne.Enabled = false;
                 // Fill in the Flow layout with all of the movie details that are filled :)
                 LoadDetailPanelWithMovieDetails(movieDetails, flowLayoutPanel2, reflectionLabel2,showtype.tv);
             }
         } */

        private void ShowDetailsOnCurrentOLVItemWithXML(VideoItem item)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In ShowDetailsOnCurrentOLVItemWithXML");
            //pbWaiting.Visible = true;
            pictureBox1.Image = null;
            flowLayoutPanel1.Controls.Clear();
            Application.DoEvents(); // allow the animated gif to show up...

            if (item.XmlPresent)
            {
                details movieDetails = item.MovieDetail;
                string fullpath = Path.GetDirectoryName(item.FullFileName);
                // get the correct sized picture
                LoadPictureBox(pictureBox1, Path.ChangeExtension(item.FullFileName, ".jpg"));
                // if (item.VOBDirectory) LoadPictureBox(pictureBox1, Path.ChangeExtension(item.FullFileName, ".jpg"));
                // else
                //     LoadPictureBox(pictureBox1, Path.GetFileNameWithoutExtension(item.FullFileName)), ".jpg"));
                //LoadPictureBox(pictureBox1, fullpath + Path.DirectorySeparatorChar + Path.ChangeExtension(RemoveIllegalPathCharacters(item.Title), ".jpg"));

                if (pictureBox1.Tag == null) btnNextImage.Enabled = false;

                btnSelectAlternateMovies.Enabled = false;
                btnSaveThisOne.Enabled = false;
                // Fill in the Flow layout with all of the movie details that are filled :)
                LoadDetailPanelWithMovieDetails(movieDetails, flowLayoutPanel1, lblMovieTitle);
            }
        }

        private void LoadPictureBox(PictureBox pictureBox, string imagepath)
        {
           /* //pictureBox.LoadAsync(imagepath);
            if (!File.Exists(imagepath))
            {
                // try if with . in filename.
                string newfilename = imagepath;
                newfilename = Path.Combine(Path.GetDirectoryName(imagepath), "." + Path.GetFileName(imagepath));
                if (!File.Exists(newfilename))
                    return;
                else
                    pictureBox.Load(newfilename);
            } else */
            pictureBox.Load(UpdateImageLocation(imagepath));
        }

        private string UpdateImageLocation(string imagepath)
        {
            if (!File.Exists(imagepath))
            {
                // try if with . in filename.
                string newfilename = imagepath;
                newfilename = Path.Combine(Path.GetDirectoryName(imagepath), "." + Path.GetFileName(imagepath));
                if (!File.Exists(newfilename))
                    return imagepath;
                else
                    return newfilename;
            }
            return imagepath;
        }

        private bool ShowDetailsOnCurrentOLVItem(VideoItem item)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In ShowDetailsOnCurrentOLVItem");
            pbTV.Image = null;
            pbTVBanner.Image = null;
            flowLayoutPanel2.Controls.Clear();
            sbStatus.Text = string.Format("Searching for and loading {1} {0}...", item.FullFileName, (item.VideoType == VideoTypeEnum.MovieType) ? "Movie" : "TV Show");
            Cursor.Current = Cursors.WaitCursor;
            Application.DoEvents(); // allow the animated gif to show up...

            if (item.XmlPresent)
            {
                ShowDetailsOnCurrentOLVItemWithXML(item);
            }
            else
            {
                // Look in the information up based on the full filename :)
                if (LoadVideoDetails(item)) // olvselectedIndex, item.CleanFileName, item.UncleanFileName))
                {
                    btnNextImage.Enabled = (pictureBox1.Tag != null);
                    btnSelectAlternateMovies.Enabled = true;
                    btnSaveThisOne.Enabled = true;
                    sbStatus.Text = "Done.";
                    Cursor.Current = Cursors.Default;
                }
                else
                {
                    // message that nothing was updated....
                    if (options.AutoAggressiveLookup)
                    {
                        aggressive = true;
                        if (LoadVideoDetails(item))
                        {
                            btnNextImage.Enabled = (pictureBox1.Tag != null);
                            btnSelectAlternateMovies.Enabled = true;
                            btnSaveThisOne.Enabled = true;
                            sbStatus.Text = "Done.";
                            Cursor.Current = Cursors.Default;
                            aggressive = false;
                            return true;
                        }
                        sbStatus.Text = "Video Not Found...";
                        Cursor.Current = Cursors.Default;
                        aggressive = false;
                        return false;
                    }
                    
                }
            }
            Cursor.Current = Cursors.Default;
            return true;

        }

        /*  private void ShowDetailsOnCurrentOLVItem(VideoItem item)
          {
              if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In ShowDetailsOnCurrentOLVItem");
              pictureBox1.Image = null;
              flowLayoutPanel1.Controls.Clear();
              sbStatus.Text = string.Format("Searching for and loading Movie {0}...", item.FullFileName);
              Cursor.Current = Cursors.WaitCursor;
              Application.DoEvents(); // allow the animated gif to show up...

              if (item.XmlPresent)
              {
                  ShowDetailsOnCurrentOLVItemWithXML(item);
              }
              else
              {
                  // Look in the information up based on the full filename :)
                  if (LoadMovieDetails(item)) // olvselectedIndex, item.CleanFileName, item.UncleanFileName))
                  {
                      btnNextImage.Enabled = (pictureBox1.Tag != null);
                      btnSelectAlternateMovies.Enabled = true;
                      btnSaveThisOne.Enabled = true;
                      sbStatus.Text = "Done.";
                      Cursor.Current = Cursors.Default;
                  }
                  else
                  {
                      // message that nothing was updated....
                      sbStatus.Text = "Movie Not Found...";
                      Cursor.Current = Cursors.Default;
                  }
              }
              Cursor.Current = Cursors.Default;
          }



          private bool ShowDetailsOnCurrentOLVItem(VideoItem item)
          {
              if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In ShowDetailsOnCurrentOLVItem");
              pbTV.Image = null;
              pbTVBanner.Image = null;
              flowLayoutPanel2.Controls.Clear();
              sbStatus.Text = string.Format("Searching for and loading tv show {0}...", item.FullFileName);
              Cursor.Current = Cursors.WaitCursor;
              Application.DoEvents(); // allow the animated gif to show up...

              if (item.XmlPresent)
              {
                  ShowDetailsOnCurrentOLVItemWithXML(item);
              }
              else
              {
                  // Look in the information up based on the full filename :)
                  if (LoadTVDetails(item)) // olvselectedIndex, item.CleanFileName, item.UncleanFileName))
                  {
                      btnTVNextImage.Enabled = (pbTV.Tag != null);
                      btnShowMoreSeries.Enabled = true;
                    
                      btnTVSaveThisOne.Enabled = true;
                      sbStatus.Text = "Done.";
                      Cursor.Current = Cursors.Default;
                  }
                  else
                  {
                      // message that nothing was updated....
                      sbStatus.Text = "Movie Not Found...";
                      Cursor.Current = Cursors.Default;
                      return false;
                  }
              }
              Cursor.Current = Cursors.Default;
              return true;
            
          }
         */

        private bool LoadTVDetails(VideoItem item)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadTVDetails");
            //pbTV.Image = null;
            pictureBox1.Image = null;
            flowLayoutPanel1.Controls.Clear();

            Application.DoEvents(); // allow the animated gif to show up...

            try
            {
                // at this point, check to see if this series has already been found and confirm, if so, then use that series info...
                // use a dictionary with the clean filename and the series id as key, if found, just pass that 
                if (InAutomationLoop)
                    if (savedSeries.ContainsKey(HttpUtility.UrlEncode(item.CleanFileName)))
                    {
                        LoadSeriesByID(savedSeries[HttpUtility.UrlEncode(item.CleanFileName)], item);
                        return true;
                    }
                string lookupterm = item.CleanFileName;
                if (this.aggressive) lookupterm = AggressiveCleanName(lookupterm);

                List<TvdbSearchResult> ser = m_tvdbHandler.SearchSeries(HttpUtility.UrlEncode(lookupterm));

                seriesFound = ser.Count;
                if (seriesFound > 1)
                {
                    btnSelectAlternateMovies.Text = string.Format("{0} Shows Found", seriesFound);
                    btnSelectAlternateMovies.Tag = lookupterm;
                    
                    if (InAutomationLoop)
                    {
                        // pop up the search form... get the result and store it... pass on the series id.
                        TvdbLanguage lang = new TvdbLanguage(10, "German", options.LanguageToReturn);
                        List<TvdbSearchResult> list =
                            m_tvdbHandler.SearchSeries(HttpUtility.UrlEncode(item.CleanFileName), lang);
                        if (list != null && list.Count > 0)
                        {
                            SearchResultForm form = new SearchResultForm(list);
                            form.StartPosition = FormStartPosition.Manual;
                            form.Left = this.Left + this.Width / 2 - form.Width / 2;
                            form.Top = this.Top + this.Height / 2 - form.Height / 2;
                            DialogResult res = form.ShowDialog();
                            if (res == DialogResult.OK)
                            {
                                // save it in the list that lives during this automation process
                                savedSeries.Add(HttpUtility.UrlEncode(item.CleanFileName), form.Selection.Id);
                                // Now do something with the series that I picked... using form.Selection.Id
                                LoadSeriesByID(form.Selection.Id, item);
                                return true;
                            } 
                            return false;
                            
                        }
                    }
                }
                else
                {
                    btnSelectAlternateMovies.Text = "Only 1 Show Found";
                    btnSelectAlternateMovies.Enabled = false;
                }

                if (seriesFound > 0)
                {
                    btnSeriesInfo.Enabled = true;
                    LoadSeriesByID(ser[seriesNumToShow].Id, item);
                    // TVcurrentlyselected.Tag = md;
                    return true;
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler(ex, "LoadTVDetails");
            }

            sbStatus.Text = "Show Not Found";
            //item.SubItems[4].Text = "No Movies Found!";
            return false;
        }

        private void LoadSeriesByID(int id, VideoItem item)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In LoadSeriesByID");
            try
            {
                TvdbLanguage lang = new TvdbLanguage(10, "German", options.LanguageToReturn);
                    //TvdbLanguage.DefaultLanguage
                if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "Before GetSeries In LoadSeriesByID");
                series = m_tvdbHandler.GetSeries(id, lang, true,
                                                 true, true, false);
                if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "After GetSeries In LoadSeriesByID");
                details md = LoadTheDetails(series, item.FullFileName, item.Season, item.Episode);
                if (md.year == "") md.year = md.firstaired;
                if (md.firstaired == "") md.firstaired = md.year;
                try
                {
                    if (md.thumbnail.Length > 0)
                    {
                        LoadPictureBox(pictureBox1, md.thumbnail[0].Value);
                        pictureBox1.Tag = string.Format("{0}.{1}.{2}.{3}", id, md.thumbnail.Length, item.Season,
                                                        item.Episode);
                        btnNextImage.Enabled = true;
                    }
                    else
                    {
                        // Generate a thumbnail with the series name....
                        LoadPictureBox(pictureBox1, "nothumb.jpg");
                    }


                    if (md.backdrop.Length > 0)
                        LoadPictureBox(pbBannerBox, md.backdrop[0].Value);


                }
                catch (Exception ex)
                {
                }

                LoadDetailPanelWithMovieDetails(md, flowLayoutPanel1, lblMovieTitle);
                item.SeriesName = series.SeriesName;
                TvdbEpisode episode =null;
                if (series.Episodes == null)
                    episode = m_tvdbHandler.GetEpisode(id, item.Season, item.Episode, TvdbEpisode.EpisodeOrdering.DefaultOrder, lang);
                else
                {
                    foreach (TvdbEpisode ep in series.Episodes   )
                    {
                        if ((ep.SeasonNumber == item.Season) && (ep.EpisodeNumber == item.Episode))
                        {
                            episode = ep;
                            break;
                        }
                        
                    }
                }
                
                item.EpisodeName = episode.EpisodeName;
                item.MovieDetail = md;
            }
            catch (Exception ex)
            {
                ExceptionHandler(ex, "LoadSeriesByID");
            }
        }
        private void LoadMovieByID(int Id, VideoItem item, int cd1, int cd2)
        {
            api = new Tmdb("f703f0d3679c29df8855db6c80f382c8");
            
            movie = api.GetMovieInfo(Id, options.LanguageToReturn);
            
            TmdbConfiguration config = api.GetConfiguration();
             Uri baseUri = new Uri(config.images.base_url);
            details md = LoadTheDetails(movie, item.FullFileName);
            md.title = ProcessTags(options.MovieTitleTemplate, md);
            if (cd1 != -1) md.title += " (CD 1)";
            if (cd2 != -1) md.title += " (CD 2)";
            int piccount = 0;
            // get the correct sized picture
            TmdbMovieImages images = api.GetMovieImages(movie.id);
            bool somethingfound = false;
            foreach (Poster poster in images.posters)
            {
                piccount++;
                if (poster.iso_639_1 == options.LanguageToReturn) // need to figure out what is the correct width... here
                {
                    somethingfound = true;
                    Uri myUri = new Uri(baseUri, "w154"+ poster.file_path);
                    LoadPictureBox(pictureBox1, myUri.AbsoluteUri);
                    pictureBox1.Tag = string.Format("{0}.{1}", movie.id, piccount);
                    btnNextImage.Enabled = true;
                    break;
                }
            }

            if (!somethingfound)
            {
                foreach (Poster poster in images.posters)
                {
                    piccount++;
                   
                        Uri myUri = new Uri(baseUri, "w154" + poster.file_path);
                        LoadPictureBox(pictureBox1, myUri.AbsoluteUri);
                        pictureBox1.Tag = string.Format("{0}.{1}", movie.id, piccount);
                        btnNextImage.Enabled = true;
                        break;
                    
                }
            }

           
            if (md.year == "") md.year = md.firstaired;
            if (md.firstaired == "") md.firstaired = md.year;

            LoadDetailPanelWithMovieDetails(md, flowLayoutPanel1, lblMovieTitle);
            // load the details back into the olv.
            item.MovieDetail = md;
            
        }

        private void TurnOnCylonWait(bool cylon)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In TurnOnCylonWait");
            sbProgress.Style = cylon ? ProgressBarStyle.Marquee : ProgressBarStyle.Blocks;
            Application.DoEvents();

        }

        private void objectListView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In objectListView1_MouseDoubleClick");
            if (objectListViewMovie.SelectedIndex > -1)
            {
                TurnOnCylonWait(true);
                timer1.Enabled = false;
                var item = (VideoItem)objectListViewMovie.SelectedObject;
                sbStatus.Text = string.Format("Searching for and loading video {0}...", item.FullFileName);
                moviesFound = 0;
                movieNumToShow = 0;
                ShowDetailsOnCurrentOLVItem(item);
                sbStatus.Text = "Load Done.";
                TurnOnCylonWait(false);
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In buttonX1_Click");
            splitContainer1.Panel2Collapsed = btnShowPanelDetail.Checked;
        }

        private void aggressiveLookupInformationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In aggressiveLookupInformationToolStripMenuItem_Click");
            if (objectListViewMovie.SelectedItems.Count > 0)
            {
                aggressive = true;
                ShowDetailsOnCurrentOLVItem((VideoItem)objectListViewMovie.SelectedObject);

                aggressive = false;
            }
        }

        private void objectListViewTV_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In objectListViewTV_MouseDoubleClick");
            if (objectListViewTV.SelectedIndex > -1)
            {
                TurnOnCylonWait(true);
                var item = (VideoItem)objectListViewTV.SelectedObject;
                Application.DoEvents();

                moviesFound = 0;
                movieNumToShow = 0;
                if (ShowDetailsOnCurrentOLVItem(item))
                {
                    if (series.Banners.Count > 0) btnSeasonInfo.Enabled = true;
                    else
                    {
                        try
                        {
                            // force the load of the series information.
                            List<TvdbSearchResult> ser = m_tvdbHandler.SearchSeries(item.GetShowName());  // this will no longer work... need the show name somehow.
                            seriesFound = ser.Count;
                            if (seriesFound > 0)
                            {
                                TvdbLanguage lang = new TvdbLanguage(10, "Duestch", "de"); //TvdbLanguage.DefaultLanguage,
                                series = m_tvdbHandler.GetSeries(ser[seriesNumToShow].Id, lang,
                                                                 false,
                                                                 false, false);
                                btnSeasonInfo.Enabled = true;
                            }
                            else btnSeasonInfo.Enabled = false;
                        }
                        catch (Exception ex)
                        {
                            ExceptionHandler(ex, "Series Lookup on Double Click");
                        }
                    }
                    sbStatus.Text = string.Format("Show {0} Loaded. Done.", item.GetShowName());
                }
                TurnOnCylonWait(false);

            }
        }

        private void chkGroupByProcessedTV_CheckedChanged(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In chkGroupByProcessedTV_CheckedChanged");
            //PopulateList(txtPath.Text, chkShowUnprocessed.Checked, lvwFileList,showtype.movie);
            if (chkGroupByProcessedTV.Checked)
            {
                objectListViewTV.ShowGroups = true;
                objectListViewTV.PrimarySortColumn = olvcXMLExists;
            }
            else
            {
                objectListViewTV.ShowGroups = false;
                objectListViewTV.PrimarySortColumn = olvcTitle;
            }
        }

        private void btnShowTVDetailPanel_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnShowTVDetailPanel_Click");
            splitContainer2.Panel2Collapsed = btnShowTVDetailPanel.Checked;
        }

        private void btnRenameTV_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnRenameTV_Click");
            var item = (VideoItem)txtRenameTV.Tag;
            //txtRenameTV.Text = RemoveIllegalPathCharacters(txtRenameTV.Text);
            File.Move(item.FullFileName, txtRenameTV.Text);
            item.FullFileName = txtRenameTV.Text;
            string cleanfilename = CleanFileName(Path.GetFileNameWithoutExtension(item.FullFileName));
            item.CleanFileName = RemoveEpisodeInformation(cleanfilename).Trim();
            btnRenameTV.Visible = false;
            btnCancelRenameTV.Visible = false;
            txtRenameTV.Visible = false;
        }

        private void btnCancelRenameTV_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In btnCancelRenameTV_Click");
            btnRenameTV.Visible = false;
            btnCancelRenameTV.Visible = false;
            txtRenameTV.Visible = false;
        }

        #region Nested type: showtype

        private enum showtype
        {
            movie,
            tv
        } ;

        #endregion

        private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In contextMenuStrip1_Opening");
            aggressiveLookupInformationToolStripMenuItem.Enabled = (tabControl1.SelectedTab.Name == "tabMovies");

        }

        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {

        }

        private void ExceptionHandler(Exception exception, string sender)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In ExceptionHandler");
            string messagestring = string.Empty;
            switch (options.VerboseErrors)
            {
                case Options.LoggingLevels.none:
                    messagestring = string.Format("Error Message: {0}",
                                                     exception.Message);
                    break;
                case Options.LoggingLevels.errors:
                    messagestring = string.Format("Error Message: {0}\nInner Exception: {1}\nStack Trace: {2}",
                                                     exception.Message,
                                                     (exception.InnerException != null)
                                                         ? exception.InnerException.Message
                                                         : "No Inner Exception", exception.StackTrace);
                    CLogger.WriteLog(ELogLevel.ERROR, messagestring);
                    break;
                case Options.LoggingLevels.verbose:
                    messagestring = string.Format("Error Message: {0}\nInner Exception: {1}\nStack Trace: {2}",
                                                     exception.Message,
                                                     (exception.InnerException != null)
                                                         ? exception.InnerException.Message
                                                         : "No Inner Exception", exception.StackTrace);
                    CLogger.WriteLog(ELogLevel.ERROR, messagestring);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            MessageBox.Show(messagestring, string.Format("Error in WDTVHubGen at {0}", sender), MessageBoxButtons.OK, MessageBoxIcon.Error,
                                MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);

        }

        /*    
         * private void txtSeriesPath_KeyDown(object sender, KeyEventArgs e)
            {
                if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In txtSeriesPath_KeyDown");
            if (e.KeyCode == Keys.Return)
            {
                btnGetShows_Click(sender, e);
            }

            } */

        private void removeExistingXMLThumbToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In removeExistingXMLThumbToolStripMenuItem_Click");
            if (tabControl1.SelectedTab.Name == "tabMovies")
            {
                // look up the currently selected Movie information and display on the screen
                // Get the currently selected item under the cursor...

                if (objectListViewMovie.SelectedItems.Count > 0)
                {
                    VideoItem mi = (VideoItem)objectListViewMovie.SelectedObject;
                    if (MessageBox.Show(string.Format("Delete XML and Cover Art associated with {0}?", mi.Title), "Are you Sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        string xmlfilename = Path.ChangeExtension(mi.FullFileName, ".xml");
                        string jpgFileName = Path.ChangeExtension(mi.FullFileName, ".jpg");
                        try
                        {
                            File.Delete(xmlfilename);
                            // clear out the picture box first...
                            pictureBox1.Image.Dispose();
                            pictureBox1.Image = null;
                            mi.ThumbPath = "";
                            mi.ThumbnailPresent = false;
                            mi.XmlPresent = false;

                            objectListViewMovie.OwnerDraw = true;
                            objectListViewMovie.SetObjects(movieList);
                            objectListViewMovie.Refresh();
                            Application.DoEvents();
                            File.Delete(jpgFileName);

                        }

                        catch (System.IO.IOException ioException)
                        {
                            MessageBox.Show(ioException.Message, "XML File Not Deleted");
                        }

                        catch (System.UnauthorizedAccessException unauthorizedAccessException)
                        {
                            MessageBox.Show("Permission Denied");
                        }
                        // force relaod by pressing "get files"
                        btnGetFiles_Click(this, new EventArgs());

                    }

                }
            }
            else
            {
                if (objectListViewTV.SelectedItems.Count > 0)
                {
                    VideoItem mi = (VideoItem)objectListViewTV.SelectedObject;
                    if (MessageBox.Show(string.Format("Delete XML and Cover Art associated with {0}?", mi.Title), "Are you Sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        string xmlfilename = Path.ChangeExtension(mi.FullFileName, ".xml");
                        string jpgfilename = Path.ChangeExtension(mi.FullFileName, ".jpg");
                        try
                        {
                            File.Delete(xmlfilename);
                            pbTV.Image.Dispose();
                            File.Delete(jpgfilename);
                        }

                        catch (System.IO.IOException)
                        {
                        }

                        catch (System.UnauthorizedAccessException unauthorizedAccessException)
                        {
                            MessageBox.Show("Permission Denied", string.Format(unauthorizedAccessException.Message));
                        }

                    }
                }
            }
        }

        private void propertiesGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            string PropertyTag = string.Empty;

            switch (e.ChangedItem.PropertyDescriptor.GetType().Name)
            {
                case "CustomPropertyDescriptor":

                    CustomProperty.CustomPropertyDescriptor cpd =
                        e.ChangedItem.PropertyDescriptor as CustomProperty.CustomPropertyDescriptor;
                    if (cpd != null)
                    {
                        CustomProperty cp = (CustomProperty)cpd.CustomProperty;
                        if (cp == null)
                        {
                            return;
                        }
                        if (cp.Value != null)
                        {
                            PropertyTag = cp.Tag.ToString();
                        }
                    }
                    break;
            }
            // Loop through the existing properties in options and save them :)
            Type myType = options.GetType();
            PropertyInfo[] pi = myType.GetProperties();
            foreach (PropertyInfo prop in pi)
                if (prop.Name == PropertyTag)
                {
                    switch (prop.PropertyType.FullName)
                    {
                        case "System.Int32":
                            prop.SetValue(options, Convert.ToInt32(e.ChangedItem.Value), null);
                            break;
                        case "System.String":
                            if (e.ChangedItem.Value is string[])
                            {
                                string list = ((string[])e.ChangedItem.Value).Aggregate(string.Empty, (current, str) => current + (str + ","));
                                prop.SetValue(options, list.Trim(','), null);
                            }
                            else
                                prop.SetValue(options, e.ChangedItem.Value, null);
                            break;
                        case "System.Boolean":
                            prop.SetValue(options, Convert.ToBoolean(e.ChangedItem.Value), null);
                            break;
                    }
                    options.SaveSettings();
                }
        }



        private void lblMultipleFilms_MouseDoubleClick(object sender, EventArgs e)
        {
            // pop up a chooser... then use this on and reload the show info....
            if (this.objectListViewMovie.SelectedObject != null)
            {
                VideoItem item = (VideoItem)objectListViewMovie.SelectedObject;

                switch (item.VideoType)
                {
                    case VideoTypeEnum.MovieType:
                        string tempCleanName = btnSelectAlternateMovies.Tag.ToString();
                        int cd1 = item.CleanFileName.IndexOf("cd1");
                        int cd2 = item.CleanFileName.IndexOf("cd2");
                        //if (cd1 != -1)
                        //    tempCleanName = tempCleanName.Remove(cd1, 3);
                        //if (cd2 != -1)
                        //    tempCleanName = tempCleanName.Remove(cd2, 3);


                        //if (aggressive) tempCleanName = AggressiveCleanName(tempCleanName);


                        var api = new Tmdb("f703f0d3679c29df8855db6c80f382c8");

                        TmdbMovieSearch movies = api.SearchMovie(tempCleanName, 1, options.LanguageToReturn); //, options.LanguageToReturn);

                        if (movies != null && movies.results.Count > 0)
                        {
                            MovieSearchResultForm form = new MovieSearchResultForm(movies.results,tempCleanName);
                            form.StartPosition = FormStartPosition.Manual;
                            form.Left = this.Left + this.Width / 2 - form.Width / 2;
                            form.Top = this.Top + this.Height / 2 - form.Height / 2;
                            DialogResult res = form.ShowDialog();
                            if (res == DialogResult.OK)
                            {
                                // Now do something with the series that I picked... using form.Selection.Id
                                LoadMovieByID(form.Selection.id, item, cd1, cd2);
                            }
                        }
                        else
                        {
                            MessageBox.Show("No results for this series");
                        }
                        break;
                    case VideoTypeEnum.TVType:
                        TvdbLanguage lang = new TvdbLanguage(10, "German", this.options.LanguageToReturn);
                        string lookupterm = btnSelectAlternateMovies.Tag.ToString();
                        List<TvdbSearchResult> list = m_tvdbHandler.SearchSeries(lookupterm, lang);
                        if (list != null && list.Count > 0)
                        {
                            SearchResultForm form = new SearchResultForm(list);
                            form.StartPosition = FormStartPosition.Manual;
                            form.Left = this.Left + this.Width / 2 - form.Width / 2;
                            form.Top = this.Top + this.Height / 2 - form.Height / 2;
                            DialogResult res = form.ShowDialog();
                            if (res == DialogResult.OK)
                            {
                                // Now do something with the series that I picked... using form.Selection.Id
                                LoadSeriesByID(form.Selection.Id, item);
                            }
                        }
                        else
                        {
                            MessageBox.Show("No results for this series");
                        }
                        break;
                    case VideoTypeEnum.AdultType:
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }


            }
        }

        private void lblMultpleTV_Click(object sender, EventArgs e)
        {
            // pop up a chooser... then use this on and reload the show info....
            if (this.objectListViewTV.SelectedObject != null)
            {
                VideoItem item = (VideoItem)objectListViewTV.SelectedObject;
                TvdbLanguage lang = new TvdbLanguage(10, "German", this.options.LanguageToReturn);
                List<TvdbSearchResult> list = m_tvdbHandler.SearchSeries(item.GetShowName(), lang);
                if (list != null && list.Count > 0)
                {
                    SearchResultForm form = new SearchResultForm(list);
                    form.StartPosition = FormStartPosition.Manual;
                    form.Left = this.Left + this.Width / 2 - form.Width / 2;
                    form.Top = this.Top + this.Height / 2 - form.Height / 2;
                    DialogResult res = form.ShowDialog();
                    if (res == DialogResult.OK)
                    {
                        // Now do something with the series that I picked... using form.Selection.Id
                        LoadSeriesByID(form.Selection.Id, item);
                    }
                }
                else
                {
                    MessageBox.Show("No results for this series");
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // pick a random background, and go get it...
            timer1.Enabled = false;
            if (timer1.Tag != null)
            {
                try
                {
                    details movieDetails = (details)timer1.Tag;


                    Random random = new Random();

                    //PictureBox pb = (PictureBox)flowLayoutPanel1.Controls.Find("BackDropPictureBox", true)[0];
                    pbBannerBox.Image = new System.Drawing.Bitmap(
                            new System.IO.MemoryStream(
                                new System.Net.WebClient().DownloadData(
                                    movieDetails.backdrop[random.Next(movieDetails.backdrop.Length)].Value)));
                }
                catch (Exception ex)
                {
                    timer1.Enabled = false;
                    return;
                }
            }
            timer1.Interval = 5000;
            timer1.Enabled = true;

        }

        private void tabControl1_TabIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab.Name != "tabMovies") timer1.Enabled = false;

        }

        private void openFolderLocationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "tabMovies":
                    if (objectListViewMovie.SelectedObject != null)
                    {
                        VideoItem VideoItem = (VideoItem)objectListViewMovie.SelectedObject;
                        Process.Start(Path.GetDirectoryName(VideoItem.FullFileName));
                    }
                    break;
                case "tabTV":
                    if (this.objectListViewTV.SelectedObject != null)
                    {
                        VideoItem VideoItem = (VideoItem)objectListViewTV.SelectedObject;
                        Process.Start(Path.GetDirectoryName(VideoItem.FullFileName));
                    }
                    break;
                case "tabOptions":
                    break;
            }



        }

        private void objectListViewMovie_SelectionChanged(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In objectListView1_ItemSelectionChanged");
            timer1.Enabled = false;
            TurnOnCylonWait(true);
            try
            {
                var item = (VideoItem)objectListViewMovie.SelectedObject;
                if (item != null)
                    if (item.XmlPresent)
                    {
                        pbBannerBox.Image = null;
                        sbStatus.Text = string.Format("Searching for and loading {1} {0}...", item.FullFileName, (item.VideoType == VideoTypeEnum.MovieType) ? "Movie" : "TV Show");
                        ShowDetailsOnCurrentOLVItemWithXML(item);
                        //timer1.Tag = item;
                        sbStatus.Text = "Load Done.";
                    }
                    else
                    {
                        pictureBox1.ImageLocation = "NotFoundBig.jpg";
                        pbBannerBox.Image = null;
                        flowLayoutPanel1.Controls.Clear();
                        timer1.Enabled = false;
                        lblMovieTitle.Visible = true;
                        lblMovieTitle.Text =
                            string.Format("<b><font size=\"+6\">No Video information. Double Click to Load</font></b>");
                    }
            }
            catch (Exception ex)
            {
                ExceptionHandler(ex, "Video OLV ItemSelectionChanged");
            }

            TurnOnCylonWait(false);
        }

        private void objectListViewTV_SelectionChanged(object sender, EventArgs e)
        {
            if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In objectListViewTV_ItemSelectionChanged");
            TurnOnCylonWait(true);
            try
            {
                var item = (VideoItem)objectListViewTV.SelectedObject;
                if (item != null)
                    if (item.XmlPresent)
                    {
                        pbTVBanner.Image = null;
                        btnSeasonInfo.Enabled = false;
                        sbStatus.Text = string.Format("Searching for and loading show {0}...", item.FullFileName);
                        ShowDetailsOnCurrentOLVItemWithXML(item);
                        // attempt to load the "screen shot" into the picture box...
                        sbStatus.Text = "Load Done.";
                    }
                    else
                    {
                        pbTV.ImageLocation = "NotFoundBig.jpg";
                        reflectionLabel2.Visible = true;
                        reflectionLabel2.Text =
                            string.Format("<b><font size=\"+6\">No Show information. Double Click to Load</font></b>");
                        pbTVBanner.Image = null;
                        flowLayoutPanel2.Controls.Clear(); // clear them out...
                    }
            }
            catch (Exception ex)
            {
                ExceptionHandler(ex, "OLVTV ItemSelectionChanged");
            }

            TurnOnCylonWait(false);
        }

        private void objectListViewMovie_FormatRow(object sender, BrightIdeasSoftware.FormatRowEventArgs e)
        {
            VideoItem VideoItem = (VideoItem)e.Model;
            /* if (!VideoItem.XmlPresent)
            {
                e.Item.BackColor = Color.LightSalmon;
            } */
        }

        private void button1_Click(object sender, EventArgs e)
        {
            objectListViewMovie.RowHeight = 25;
        }

        private void tsmDetails_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "tabMovies":
                    objectListViewMovie.View = View.Details;
                    break;
                case "tabTV":
                    objectListViewTV.View = View.Details;
                    break;
                case "tabOptions":
                    break;
            }
        }



        private void tsmTiles_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "tabMovies":
                    objectListViewMovie.TileSize = new Size(500, 120);
                    objectListViewMovie.CheckBoxes = false;
                    objectListViewMovie.View = View.Tile;
                    break;
                case "tabTV":
                    objectListViewTV.View = View.Tile;
                    break;
                case "tabOptions":
                    break;
            }
        }


        private void tsm100_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "tabMovies":
                    objectListViewMovie.RowHeight = 100;
                    break;
                case "tabTV":
                    objectListViewTV.RowHeight = 100;
                    break;
                case "tabOptions":
                    break;
            }
        }

        private void tsm75_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "tabMovies":
                    objectListViewMovie.RowHeight = 75;
                    break;
                case "tabTV":
                    objectListViewTV.RowHeight = 75;
                    break;
                case "tabOptions":
                    break;
            }
        }

        private void tsm50_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "tabMovies":
                    objectListViewMovie.RowHeight = 50;
                    break;
                case "tabTV":
                    objectListViewTV.RowHeight = 50;
                    break;
                case "tabOptions":
                    break;
            }
        }

        private void tsm25_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "tabMovies":
                    objectListViewMovie.RowHeight = 25;
                    break;
                case "tabTV":
                    objectListViewTV.RowHeight = 25;
                    break;
                case "tabOptions":
                    break;
            }
        }

        private void tabControl1_SelectedTabChanging(object sender, DevComponents.DotNetBar.TabStripTabChangingEventArgs e)
        {
            if (e.OldTab.Name == "tabOptions")
            {
                // Do anything post changes that you want....
                objectListViewMovie.UseTranslucentHotItem = options.ShowCards;
                //objectListViewTV.UseTranslucentHotItem = options.ShowCards;
                //objectListViewTV.HotItemStyle.Overlay = new TVCardOverlay();
                //objectListViewTV.HotItemStyle = this.objectListViewTV.HotItemStyle;
                objectListViewMovie.HotItemStyle.Overlay = new MovieCardOverlay();
                objectListViewMovie.HotItemStyle = this.objectListViewMovie.HotItemStyle;

            }
        }

        private void txtPath_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                btnGetFiles_Click(sender, e);
            }
        }

        private void txtRenameFile_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                btnRenameFile_Click(sender, e);
            }
        }

        private void btnToggleHidden_Click(object sender, EventArgs e)
        {
            // tell the user they are about to make a big change...
            DialogResult answer =
                MessageBox.Show(
                    string.Format("This will rename all JPGs in {0} and subdirectories.  Select YES to hide, Select NO to unhide, and cancel to Cancel", cboPath.Text),
                    "Hide JPGs",MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation,
                    MessageBoxDefaultButton.Button1);
            switch (answer)
            {
                case DialogResult.None:
                    break;
                case DialogResult.OK:
                    break;
                case DialogResult.Cancel:
                    break;
                case DialogResult.Abort:
                    break;
                case DialogResult.Retry:
                    break;
                case DialogResult.Ignore:
                    break;
                case DialogResult.Yes:
                    MessageBox.Show("Done", string.Format("Hid {0} files", HideJPGs(cboPath.Text, true)), MessageBoxButtons.OK);
                    break;
                case DialogResult.No:
                    MessageBox.Show("Done", string.Format("Un-Hid {0} files", HideJPGs(cboPath.Text, false)), MessageBoxButtons.OK);
                    
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

        }

        private int HideJPGs(string path, bool hide)
        {
            // perhaps attempt to "unload" the olv and then rename, then reload it.. at the end.
            objectListViewMovie.Items.Clear();
            DirectoryInfo d = new DirectoryInfo(path);
            FileInfo[] infos = d.GetFiles("*.jpg", SearchOption.AllDirectories);
            int filecount = 0;
            foreach (FileInfo f in infos)
            {
                // Do the renaming here
                string newfilename;
                if (hide)
                {
                    if (f.Name[0] != '.')
                    {
                        newfilename = Path.Combine(f.Directory.ToString(), "." + f.Name);
                        if (!File.Exists(newfilename))
                        {
                            File.Move(f.FullName, newfilename);
                            filecount++;
                        }
                    }
                }
                else
                {
                    if (f.Name[0] == '.')
                    {
                        newfilename = Path.Combine(f.Directory.ToString(), f.Name.TrimStart('.'));
                        if (!File.Exists(newfilename))
                        {
                            File.Move(f.FullName, newfilename);
                            filecount++;
                        }

                    }

                }

            }
            btnGetFiles_Click(this, new EventArgs());
            return filecount;
            
        }

        private void cboPath_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                btnGetFiles_Click(sender, e);
            }
        }

        private void cboPath_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnGetFiles.Enabled = true;
            btnToggleHidden.Enabled = true;
        }

        private void manuallySearchForTitleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Load up the manual search window and then let it happen from there :)

            

           if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In manuallySearchfortitletoolstripmenuitem");
           
               if (objectListViewMovie.SelectedItems.Count > 0)
                {
                    frmManualSearch manualSearch = new frmManualSearch();
                    VideoItem item = (VideoItem) objectListViewMovie.SelectedObject;
                    manualSearch.txtTitle.Text = item.CleanFileName;
                    manualSearch.rdoMovie.Checked = item.VideoType == VideoTypeEnum.MovieType;
                    manualSearch.rdoTVSeries.Checked = item.VideoType == VideoTypeEnum.TVType;

                    if (item.VideoType == VideoTypeEnum.TVType)
                    {
                        manualSearch.txtSeason.Text = item.Season.ToString();
                        manualSearch.txtEpisode.Text = item.Episode.ToString();
                    }
                    DialogResult result = manualSearch.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        // determine type of search to launch....
                        // Movie Search
                        if (manualSearch.rdoMovie.Checked)
                        {
                            string tempCleanName = manualSearch.txtTitle.Text;
                            int cd1 = item.CleanFileName.IndexOf("cd1");
                            int cd2 = item.CleanFileName.IndexOf("cd2");

                            api = new Tmdb("f703f0d3679c29df8855db6c80f382c8");
                            //TmdbMovie[] movies = null;
                            TmdbMovieSearch movies = null;
                            TmdbMovie movie = null;
                            if (manualSearch.txtIMDBNumber.Text != "")
                            {
                                movie = api.GetMovieByIMDB(manualSearch.txtIMDBNumber.Text.Trim(' '));
                                if (movie.imdb_id == null) movie = null;
                            }
                            else
                                movies = api.SearchMovie(tempCleanName, 1, options.LanguageToReturn);
                            //, options.LanguageToReturn);

                            if (movies != null && movies.results.Count > 0)
                            {
                                manualSearch.Hide();
                                MovieSearchResultForm form = new MovieSearchResultForm(movies.results,tempCleanName);
                                form.StartPosition = FormStartPosition.Manual;
                                form.Left = this.Left + this.Width/2 - form.Width/2;
                                form.Top = this.Top + this.Height/2 - form.Height/2;
                                DialogResult res = form.ShowDialog();
                                if (res == DialogResult.OK)
                                {
                                    // Now do something with the series that I picked... using form.Selection.Id
                                    LoadMovieByID(form.Selection.id, item, cd1, cd2);
                                    btnSaveThisOne.Enabled = true;
                                    // force the item type to movie because manual can change it.
                                    item.VideoType = VideoTypeEnum.MovieType;
                                    
                                }
                            }
                            else
                                if (movie != null)
                                {
                                    manualSearch.Hide();
                                    MovieSearchResultForm form = new MovieSearchResultForm(movie,tempCleanName);
                                    form.StartPosition = FormStartPosition.Manual;
                                    form.Left = this.Left + this.Width / 2 - form.Width / 2;
                                    form.Top = this.Top + this.Height / 2 - form.Height / 2;
                                    DialogResult res = form.ShowDialog();
                                    if (res == DialogResult.OK)
                                    {
                                        // Now do something with the series that I picked... using form.Selection.Id
                                        LoadMovieByID(form.Selection.id, item, cd1, cd2);
                                        btnSaveThisOne.Enabled = true;
                                        // force the item type to movie because manual can change it.
                                        item.VideoType = VideoTypeEnum.MovieType;

                                    } 
                                } else
                            {
                                MessageBox.Show("No results for this Movie Search");
                            }
                        } else // must be a tv show
                        {
                            TvdbLanguage lang = new TvdbLanguage(10, "German", this.options.LanguageToReturn);
                            string lookupterm = manualSearch.txtTitle.Text;
                            item.Season = Convert.ToInt32(manualSearch.txtSeason.Text);
                            item.Episode = Convert.ToInt32(manualSearch.txtEpisode.Text);

                            List<TvdbSearchResult> list = m_tvdbHandler.SearchSeries(lookupterm, lang);
                            if (list != null && list.Count > 0)
                            {
                                SearchResultForm form = new SearchResultForm(list);
                                form.StartPosition = FormStartPosition.Manual;
                                form.Left = this.Left + this.Width / 2 - form.Width / 2;
                                form.Top = this.Top + this.Height / 2 - form.Height / 2;
                                DialogResult res = form.ShowDialog();
                                if (res == DialogResult.OK)
                                {
                                    // Now do something with the series that I picked... using form.Selection.Id
                                    LoadSeriesByID(form.Selection.Id, item);
                                    btnSaveThisOne.Enabled = true;
                                    btnSeriesInfo.Enabled = true;
                                    item.VideoType = VideoTypeEnum.TVType;
                                }
                            }
                            else
                            {
                                MessageBox.Show("No results for this series");
                            }
                        }
                    }
                }
        }

        private void moveToAnotherFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // get the filename information, move the movie file, the xml and the .jpg also move teh hidden folder about it...
           
 
            // Get the item in question
            if (objectListViewMovie.SelectedIndex > -1)
            {
                var item = (VideoItem) objectListViewMovie.SelectedObject;

                string filename = item.FullFileName;
                bool XMLProcessed = File.Exists(Path.ChangeExtension(filename, "xml"));
                bool JPGProcessed = File.Exists(UpdateImageLocation(Path.ChangeExtension(filename, "jpg")));
                bool SubsPresent = SubPresent(filename);
                string hiddenfilename = Path.Combine(Path.GetDirectoryName(filename), "." + Path.GetFileName(filename));
                hiddenfilename = Path.ChangeExtension(hiddenfilename, ".backdrop");
                bool HiddenFolderPresent = Directory.Exists(hiddenfilename);

                //Get the destination directory
                folderBrowserDialog1.SelectedPath = Path.GetDirectoryName(filename);
                folderBrowserDialog1.ShowNewFolderButton = true;
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)

                //Confirm the move
                {
                    string msgtext = string.Format("Move Video {0}{1}{2}{3}{4} to Folder {5}", Path.GetFileName(filename),
                                                   XMLProcessed ? "XML file," : "", JPGProcessed ? "JPG file," : "",
                                                   SubsPresent ? "Subs," : "",
                                                   HiddenFolderPresent ? "Hidden Backdrops," : "",
                                                   folderBrowserDialog1.SelectedPath);
                    if (MessageBox.Show(msgtext,"Move Video?",MessageBoxButtons.OKCancel,MessageBoxIcon.Question)==DialogResult.OK)
                    {
                        // Move them all...
                        File.Move(filename, Path.Combine(folderBrowserDialog1.SelectedPath, filename));
                    }
                }
            }
        }

        private void renameBackToOriginalNameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Get the original name from the xml and rename the file back...
            var item = (VideoItem) objectListViewMovie.SelectedObject;
            string originalName = item.MovieDetail.prevtitle;
            string originalFullName = Path.Combine(Path.GetDirectoryName(item.FullFileName), originalName); 

            File.Move(item.FullFileName, originalFullName);
        }

        private void objectListViewMovie_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
        {
            // save the column widths objects, so that on startup they are put back...
            
            if (!StartingUp)
            {
                colwidths = new List<int>();
                foreach (ColumnHeader column in objectListViewMovie.Columns)
                {
                    colwidths.Add(column.Width);

                }
                Utilities.SerializeObject(colwidths, @"ColumnWidths.xml");
            }
        }

        private void objectListViewMovie_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btnUserImage_Click(object sender, EventArgs e)
        {
            // let the user pic a different image for the movie currently selected, then allow them to save over the existing image.
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                LoadPictureBox(pictureBox1, openFileDialog1.FileName);
                userImage = true;
                btnSaveThisOne.Enabled = true;
            }
        }
    }



    }